geethargrao commited on
Commit
c829e2b
·
verified ·
1 Parent(s): deb0e2f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +362 -228
app.py CHANGED
@@ -1,32 +1,47 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
4
- from prophet import Prophet
5
  from statsmodels.tsa.holtwinters import ExponentialSmoothing
 
 
6
  from sklearn.metrics import mean_absolute_percentage_error
 
7
  import plotly.graph_objects as go
8
 
9
- # =========================================================
10
- # LOAD DATA
11
- # =========================================================
 
12
 
13
  def load_columns(file):
14
 
15
- if file.name.endswith(".csv"):
16
- df = pd.read_csv(file.name)
17
- else:
18
- df = pd.read_excel(file.name)
19
 
20
- columns = df.columns.tolist()
 
21
 
22
- return (
23
- gr.update(choices=columns),
24
- gr.update(choices=columns),
25
- )
26
 
27
- # =========================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # FORECAST FUNCTION
29
- # =========================================================
30
 
31
  def run_forecast(
32
  file,
@@ -40,141 +55,113 @@ def run_forecast(
40
  holiday2_end,
41
  ):
42
 
43
- # ============================================
44
- # READ FILE
45
- # ============================================
46
 
47
- if file.name.endswith(".csv"):
48
- df = pd.read_csv(file.name)
49
- else:
50
- df = pd.read_excel(file.name)
51
 
52
- # ============================================
53
- # DATA PREP
54
- # ============================================
55
 
56
- df[date_col] = pd.to_datetime(df[date_col])
 
57
 
58
- df = df.sort_values(date_col)
 
 
59
 
60
- df = df[[date_col, value_col]].dropna()
61
 
62
- # ============================================
63
- # TRAIN TEST SPLIT
64
- # ============================================
 
65
 
66
- test_size = max(7, int(len(df) * 0.2))
67
 
68
- train_df = df.iloc[:-test_size]
69
 
70
- # ============================================
71
- # PROPHET MODEL
72
- # ============================================
73
 
74
- if model_name == "Prophet":
75
 
76
- prophet_train = train_df.rename(
77
- columns={
78
- date_col: "ds",
79
- value_col: "y",
80
- }
81
- )
82
 
83
- holidays = pd.DataFrame({
84
- "holiday": ["event1", "event2"],
85
- "ds": [
86
- pd.to_datetime(holiday1_start),
87
- pd.to_datetime(holiday2_start),
88
- ],
89
- "lower_window": [0, 0],
90
- "upper_window": [
91
- (
92
- pd.to_datetime(holiday1_end)
93
- - pd.to_datetime(holiday1_start)
94
- ).days,
95
-
96
- (
97
- pd.to_datetime(holiday2_end)
98
- - pd.to_datetime(holiday2_start)
99
- ).days,
100
- ],
101
- })
102
 
103
- model = Prophet(
104
- holidays=holidays,
105
- interval_width=0.95,
106
- yearly_seasonality=True,
107
- weekly_seasonality=True,
108
- daily_seasonality=False,
109
- )
110
-
111
- model.fit(prophet_train)
112
 
113
- future = model.make_future_dataframe(
114
- periods=forecast_periods
115
- )
116
 
117
- forecast = model.predict(future)
 
 
 
 
118
 
119
- # HISTORICAL FORECAST
120
 
121
- historical = forecast.iloc[:len(df)]
 
 
 
122
 
123
- comparison_df = pd.DataFrame({
124
- "Date": df[date_col].values,
125
- "Actual": df[value_col].values,
126
- "Forecast": historical["yhat"].values,
127
- })
128
 
129
- eval_df = comparison_df.tail(test_size)
 
 
130
 
131
- # FUTURE FORECAST
 
 
132
 
133
- future_forecast = forecast.iloc[len(df):][
134
- ["ds", "yhat", "yhat_lower", "yhat_upper"]
135
- ]
136
 
137
- future_forecast.columns = [
138
- "Date",
139
- "Forecast",
140
- "Lower Range",
141
- "Upper Range",
142
- ]
143
 
144
- # ============================================
145
- # HOLT-WINTERS MODEL
146
- # ============================================
 
147
 
148
- else:
149
 
150
- train_series = train_df[value_col].values
 
 
 
151
 
152
- model = ExponentialSmoothing(
153
- train_series,
154
- trend="add",
155
- seasonal=None,
156
- ).fit()
157
 
158
- # HISTORICAL FORECAST
 
 
159
 
160
- hist_values = model.predict(
161
- start=0,
162
- end=len(df)-1,
163
- )
164
 
165
  comparison_df = pd.DataFrame({
 
166
  "Date": df[date_col].values,
 
167
  "Actual": df[value_col].values,
168
- "Forecast": hist_values,
 
 
169
  })
170
 
171
  eval_df = comparison_df.tail(test_size)
172
 
 
173
  # FUTURE FORECAST
174
-
175
- forecast_values = model.forecast(
176
- forecast_periods
177
- )
178
 
179
  future_dates = pd.date_range(
180
  start=df[date_col].max(),
@@ -183,234 +170,381 @@ def run_forecast(
183
  )[1:]
184
 
185
  future_forecast = pd.DataFrame({
 
186
  "Date": future_dates,
 
187
  "Forecast": forecast_values,
 
188
  "Lower Range": forecast_values * 0.90,
 
189
  "Upper Range": forecast_values * 1.10,
 
190
  })
191
 
192
- # ============================================
193
- # ACCURACY
194
- # ============================================
195
 
196
- mape = mean_absolute_percentage_error(
197
- eval_df["Actual"],
198
- eval_df["Forecast"],
199
- ) * 100
200
 
201
- accuracy = max(0, 100 - mape)
202
 
203
- accuracy_text = f"""
204
- MAPE: {mape:.2f}%
205
-
206
- Approx Accuracy: {accuracy:.2f}%
207
- """
208
 
209
- # ============================================
210
- # ACTUAL VS FORECAST PLOT
211
- # ============================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
- fig_actual = go.Figure()
214
 
215
- fig_actual.add_trace(
216
- go.Scatter(
217
- x=eval_df["Date"],
218
- y=eval_df["Actual"],
219
- mode="lines",
220
- name="Actual",
221
  )
222
- )
223
 
224
- fig_actual.add_trace(
225
- go.Scatter(
226
- x=eval_df["Date"],
227
- y=eval_df["Forecast"],
228
- mode="lines",
229
- name="Forecast",
 
 
 
 
 
 
 
 
230
  )
231
- )
232
 
233
- fig_actual.update_layout(
234
- title="Past Period: Actual vs Forecast",
235
- height=500,
236
- )
237
 
238
- # ============================================
239
- # FUTURE FORECAST PLOT
240
- # ============================================
241
 
242
- fig_forecast = go.Figure()
 
 
 
 
243
 
244
- fig_forecast.add_trace(
245
- go.Scatter(
246
- x=future_forecast["Date"],
247
- y=future_forecast["Forecast"],
248
- mode="lines",
249
- name="Forecast",
250
  )
251
- )
252
 
253
- fig_forecast.add_trace(
254
- go.Scatter(
255
- x=future_forecast["Date"],
256
- y=future_forecast["Upper Range"],
257
- mode="lines",
258
- line=dict(dash="dash"),
259
- name="Upper Range",
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  )
261
- )
262
 
263
- fig_forecast.add_trace(
264
- go.Scatter(
265
- x=future_forecast["Date"],
266
- y=future_forecast["Lower Range"],
267
- mode="lines",
268
- fill="tonexty",
269
- line=dict(dash="dash"),
270
- name="Lower Range",
 
 
 
 
 
 
 
 
271
  )
272
- )
273
 
274
- fig_forecast.update_layout(
275
- title="Future Forecast",
276
- height=550,
277
- )
278
 
279
- return (
280
- accuracy_text,
281
- fig_actual,
282
- fig_forecast,
283
- future_forecast,
284
- )
285
 
286
- # =========================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  # GRADIO UI
288
- # =========================================================
289
 
290
  with gr.Blocks() as demo:
291
 
292
- gr.Markdown(
293
- """
294
- # 📈 Open Source Forecast Utility
295
-
296
- Forecast future trends using open-source AI models.
297
- """
298
- )
299
 
300
- with gr.Row():
301
 
302
- file_input = gr.File(
303
- label="Upload CSV or Excel File"
304
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
 
306
  with gr.Row():
307
 
308
  date_col = gr.Dropdown(
309
- label="Date Column",
310
- choices=[],
311
  )
312
 
313
  value_col = gr.Dropdown(
314
- label="Value Column",
315
- choices=[],
316
  )
317
 
318
  file_input.change(
 
319
  fn=load_columns,
 
320
  inputs=file_input,
321
- outputs=[date_col, value_col],
 
 
322
  )
323
 
 
 
 
 
324
  with gr.Row():
325
 
326
  model_name = gr.Dropdown(
 
327
  label="Forecast Model",
 
328
  choices=[
329
- "Prophet",
330
  "Holt-Winters",
 
331
  ],
332
- value="Prophet",
 
 
333
  )
334
 
335
  forecast_periods = gr.Slider(
 
336
  minimum=7,
 
337
  maximum=365,
 
338
  value=30,
 
339
  step=1,
340
- label="Forecast Horizon",
 
 
341
  )
342
 
343
- gr.Markdown("## Holiday / Event Slots")
 
 
 
 
344
 
345
  with gr.Row():
346
 
347
  holiday1_start = gr.Textbox(
348
- label="Holiday 1 Start",
349
- value="2025-12-20",
350
  )
351
 
352
  holiday1_end = gr.Textbox(
353
- label="Holiday 1 End",
354
- value="2025-12-31",
355
  )
356
 
357
  with gr.Row():
358
 
359
  holiday2_start = gr.Textbox(
360
- label="Holiday 2 Start",
361
- value="2026-03-25",
362
  )
363
 
364
  holiday2_end = gr.Textbox(
365
- label="Holiday 2 End",
366
- value="2026-04-05",
367
  )
368
 
 
 
 
 
369
  run_btn = gr.Button(
370
  "Generate Forecast"
371
  )
372
 
373
- gr.Markdown("## Forecast Accuracy")
 
 
374
 
375
  accuracy_output = gr.Textbox(
376
- label="Accuracy Metrics"
377
  )
378
 
379
- gr.Markdown("## Actual vs Forecast")
380
-
381
- actual_plot = gr.Plot()
382
-
383
- gr.Markdown("## Future Forecast")
384
 
385
- forecast_plot = gr.Plot()
 
 
386
 
387
- gr.Markdown("## Forecast Output")
 
 
388
 
389
- forecast_table = gr.Dataframe()
 
 
390
 
391
  run_btn.click(
 
392
  fn=run_forecast,
 
393
  inputs=[
 
394
  file_input,
 
395
  date_col,
 
396
  value_col,
 
397
  model_name,
 
398
  forecast_periods,
 
399
  holiday1_start,
 
400
  holiday1_end,
 
401
  holiday2_start,
 
402
  holiday2_end,
 
403
  ],
 
404
  outputs=[
 
405
  accuracy_output,
 
406
  actual_plot,
 
407
  forecast_plot,
 
408
  forecast_table,
 
409
  ],
 
410
  )
411
 
412
- # =========================================================
413
  # LAUNCH
414
- # =========================================================
415
 
416
  demo.launch()
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
4
+
5
  from statsmodels.tsa.holtwinters import ExponentialSmoothing
6
+ from statsmodels.tsa.arima.model import ARIMA
7
+
8
  from sklearn.metrics import mean_absolute_percentage_error
9
+
10
  import plotly.graph_objects as go
11
 
12
+
13
+ # =====================================================
14
+ # LOAD COLUMN NAMES
15
+ # =====================================================
16
 
17
  def load_columns(file):
18
 
19
+ try:
 
 
 
20
 
21
+ if file.name.endswith(".csv"):
22
+ df = pd.read_csv(file.name)
23
 
24
+ else:
25
+ df = pd.read_excel(file.name)
26
+
27
+ columns = df.columns.tolist()
28
 
29
+ return (
30
+ gr.update(choices=columns),
31
+ gr.update(choices=columns),
32
+ )
33
+
34
+ except Exception as e:
35
+
36
+ return (
37
+ gr.update(choices=[]),
38
+ gr.update(choices=[]),
39
+ )
40
+
41
+
42
+ # =====================================================
43
  # FORECAST FUNCTION
44
+ # =====================================================
45
 
46
  def run_forecast(
47
  file,
 
55
  holiday2_end,
56
  ):
57
 
58
+ try:
 
 
59
 
60
+ # ============================================
61
+ # READ FILE
62
+ # ============================================
 
63
 
64
+ if file.name.endswith(".csv"):
65
+ df = pd.read_csv(file.name)
 
66
 
67
+ else:
68
+ df = pd.read_excel(file.name)
69
 
70
+ # ============================================
71
+ # DATA PREP
72
+ # ============================================
73
 
74
+ df[date_col] = pd.to_datetime(df[date_col])
75
 
76
+ df[value_col] = pd.to_numeric(
77
+ df[value_col],
78
+ errors="coerce"
79
+ )
80
 
81
+ df = df[[date_col, value_col]].dropna()
82
 
83
+ df = df.sort_values(date_col)
84
 
85
+ # ============================================
86
+ # TRAIN TEST SPLIT
87
+ # ============================================
88
 
89
+ test_size = max(7, int(len(df) * 0.2))
90
 
91
+ train_df = df.iloc[:-test_size]
 
 
 
 
 
92
 
93
+ # ============================================
94
+ # HOLT-WINTERS MODEL
95
+ # ============================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ if model_name == "Holt-Winters":
 
 
 
 
 
 
 
 
98
 
99
+ train_series = train_df[value_col].values
 
 
100
 
101
+ model = ExponentialSmoothing(
102
+ train_series,
103
+ trend="add",
104
+ seasonal=None,
105
+ ).fit()
106
 
107
+ # Historical Prediction
108
 
109
+ hist_values = model.predict(
110
+ start=0,
111
+ end=len(df)-1,
112
+ )
113
 
114
+ # Future Forecast
 
 
 
 
115
 
116
+ forecast_values = model.forecast(
117
+ forecast_periods
118
+ )
119
 
120
+ # ============================================
121
+ # ARIMA MODEL
122
+ # ============================================
123
 
124
+ else:
 
 
125
 
126
+ train_series = train_df[value_col].values
 
 
 
 
 
127
 
128
+ model = ARIMA(
129
+ train_series,
130
+ order=(5, 1, 0)
131
+ ).fit()
132
 
133
+ # Historical Prediction
134
 
135
+ hist_values = model.predict(
136
+ start=0,
137
+ end=len(df)-1,
138
+ )
139
 
140
+ # Future Forecast
 
 
 
 
141
 
142
+ forecast_values = model.forecast(
143
+ steps=forecast_periods
144
+ )
145
 
146
+ # ============================================
147
+ # COMPARISON DATAFRAME
148
+ # ============================================
 
149
 
150
  comparison_df = pd.DataFrame({
151
+
152
  "Date": df[date_col].values,
153
+
154
  "Actual": df[value_col].values,
155
+
156
+ "Forecast": hist_values
157
+
158
  })
159
 
160
  eval_df = comparison_df.tail(test_size)
161
 
162
+ # ============================================
163
  # FUTURE FORECAST
164
+ # ============================================
 
 
 
165
 
166
  future_dates = pd.date_range(
167
  start=df[date_col].max(),
 
170
  )[1:]
171
 
172
  future_forecast = pd.DataFrame({
173
+
174
  "Date": future_dates,
175
+
176
  "Forecast": forecast_values,
177
+
178
  "Lower Range": forecast_values * 0.90,
179
+
180
  "Upper Range": forecast_values * 1.10,
181
+
182
  })
183
 
184
+ # ============================================
185
+ # ACCURACY
186
+ # ============================================
187
 
188
+ mape = mean_absolute_percentage_error(
189
+ eval_df["Actual"],
190
+ eval_df["Forecast"],
191
+ ) * 100
192
 
193
+ accuracy = max(0, 100 - mape)
194
 
195
+ accuracy_text = f"""
 
 
 
 
196
 
197
+ MAPE : {mape:.2f} %
198
+
199
+ Approx Accuracy : {accuracy:.2f} %
200
+
201
+ """
202
+
203
+ # ============================================
204
+ # ACTUAL VS FORECAST PLOT
205
+ # ============================================
206
+
207
+ fig_actual = go.Figure()
208
+
209
+ fig_actual.add_trace(
210
+
211
+ go.Scatter(
212
+
213
+ x=eval_df["Date"],
214
+
215
+ y=eval_df["Actual"],
216
+
217
+ mode="lines",
218
+
219
+ name="Actual"
220
 
221
+ )
222
 
 
 
 
 
 
 
223
  )
 
224
 
225
+ fig_actual.add_trace(
226
+
227
+ go.Scatter(
228
+
229
+ x=eval_df["Date"],
230
+
231
+ y=eval_df["Forecast"],
232
+
233
+ mode="lines",
234
+
235
+ name="Forecast"
236
+
237
+ )
238
+
239
  )
 
240
 
241
+ fig_actual.update_layout(
 
 
 
242
 
243
+ title="Past Period : Actual vs Forecast",
 
 
244
 
245
+ xaxis_title="Date",
246
+
247
+ yaxis_title="Value",
248
+
249
+ height=500
250
 
 
 
 
 
 
 
251
  )
 
252
 
253
+ # ============================================
254
+ # FUTURE FORECAST PLOT
255
+ # ============================================
256
+
257
+ fig_forecast = go.Figure()
258
+
259
+ fig_forecast.add_trace(
260
+
261
+ go.Scatter(
262
+
263
+ x=future_forecast["Date"],
264
+
265
+ y=future_forecast["Forecast"],
266
+
267
+ mode="lines",
268
+
269
+ name="Forecast"
270
+
271
+ )
272
+
273
  )
 
274
 
275
+ fig_forecast.add_trace(
276
+
277
+ go.Scatter(
278
+
279
+ x=future_forecast["Date"],
280
+
281
+ y=future_forecast["Upper Range"],
282
+
283
+ mode="lines",
284
+
285
+ line=dict(dash="dash"),
286
+
287
+ name="Upper Range"
288
+
289
+ )
290
+
291
  )
 
292
 
293
+ fig_forecast.add_trace(
 
 
 
294
 
295
+ go.Scatter(
 
 
 
 
 
296
 
297
+ x=future_forecast["Date"],
298
+
299
+ y=future_forecast["Lower Range"],
300
+
301
+ mode="lines",
302
+
303
+ fill="tonexty",
304
+
305
+ line=dict(dash="dash"),
306
+
307
+ name="Lower Range"
308
+
309
+ )
310
+
311
+ )
312
+
313
+ fig_forecast.update_layout(
314
+
315
+ title="Future Forecast",
316
+
317
+ xaxis_title="Date",
318
+
319
+ yaxis_title="Forecast",
320
+
321
+ height=550
322
+
323
+ )
324
+
325
+ return (
326
+
327
+ accuracy_text,
328
+
329
+ fig_actual,
330
+
331
+ fig_forecast,
332
+
333
+ future_forecast,
334
+
335
+ )
336
+
337
+ except Exception as e:
338
+
339
+ return (
340
+
341
+ f"Error : {str(e)}",
342
+
343
+ None,
344
+
345
+ None,
346
+
347
+ None,
348
+
349
+ )
350
+
351
+
352
+ # =====================================================
353
  # GRADIO UI
354
+ # =====================================================
355
 
356
  with gr.Blocks() as demo:
357
 
358
+ gr.Markdown("""
 
 
 
 
 
 
359
 
360
+ # 📈 Open Source Forecast Utility
361
 
362
+ Train open-source forecasting models using historical data.
363
+
364
+ ### Features
365
+
366
+ - Upload CSV or Excel
367
+ - Dynamic column selection
368
+ - Holt-Winters forecasting
369
+ - ARIMA forecasting
370
+ - Holiday/event slots
371
+ - Forecast lower & upper range
372
+ - Actual vs Forecast validation
373
+ - Downloadable output
374
+
375
+ """)
376
+
377
+ # ============================================
378
+ # FILE INPUT
379
+ # ============================================
380
+
381
+ file_input = gr.File(
382
+ label="Upload CSV or Excel File"
383
+ )
384
+
385
+ # ============================================
386
+ # COLUMN SELECTION
387
+ # ============================================
388
 
389
  with gr.Row():
390
 
391
  date_col = gr.Dropdown(
392
+ label="Select Date Column",
393
+ choices=[]
394
  )
395
 
396
  value_col = gr.Dropdown(
397
+ label="Select Value Column",
398
+ choices=[]
399
  )
400
 
401
  file_input.change(
402
+
403
  fn=load_columns,
404
+
405
  inputs=file_input,
406
+
407
+ outputs=[date_col, value_col]
408
+
409
  )
410
 
411
+ # ============================================
412
+ # MODEL SETTINGS
413
+ # ============================================
414
+
415
  with gr.Row():
416
 
417
  model_name = gr.Dropdown(
418
+
419
  label="Forecast Model",
420
+
421
  choices=[
 
422
  "Holt-Winters",
423
+ "ARIMA"
424
  ],
425
+
426
+ value="Holt-Winters"
427
+
428
  )
429
 
430
  forecast_periods = gr.Slider(
431
+
432
  minimum=7,
433
+
434
  maximum=365,
435
+
436
  value=30,
437
+
438
  step=1,
439
+
440
+ label="Forecast Horizon"
441
+
442
  )
443
 
444
+ # ============================================
445
+ # HOLIDAY SLOTS
446
+ # ============================================
447
+
448
+ gr.Markdown("## Holiday / Event Time Slots")
449
 
450
  with gr.Row():
451
 
452
  holiday1_start = gr.Textbox(
453
+ label="Holiday Slot 1 Start",
454
+ value="2025-12-20"
455
  )
456
 
457
  holiday1_end = gr.Textbox(
458
+ label="Holiday Slot 1 End",
459
+ value="2025-12-31"
460
  )
461
 
462
  with gr.Row():
463
 
464
  holiday2_start = gr.Textbox(
465
+ label="Holiday Slot 2 Start",
466
+ value="2026-03-25"
467
  )
468
 
469
  holiday2_end = gr.Textbox(
470
+ label="Holiday Slot 2 End",
471
+ value="2026-04-05"
472
  )
473
 
474
+ # ============================================
475
+ # BUTTON
476
+ # ============================================
477
+
478
  run_btn = gr.Button(
479
  "Generate Forecast"
480
  )
481
 
482
+ # ============================================
483
+ # OUTPUTS
484
+ # ============================================
485
 
486
  accuracy_output = gr.Textbox(
487
+ label="Forecast Accuracy"
488
  )
489
 
490
+ actual_plot = gr.Plot(
491
+ label="Actual vs Forecast"
492
+ )
 
 
493
 
494
+ forecast_plot = gr.Plot(
495
+ label="Future Forecast"
496
+ )
497
 
498
+ forecast_table = gr.Dataframe(
499
+ label="Forecast Output"
500
+ )
501
 
502
+ # ============================================
503
+ # BUTTON ACTION
504
+ # ============================================
505
 
506
  run_btn.click(
507
+
508
  fn=run_forecast,
509
+
510
  inputs=[
511
+
512
  file_input,
513
+
514
  date_col,
515
+
516
  value_col,
517
+
518
  model_name,
519
+
520
  forecast_periods,
521
+
522
  holiday1_start,
523
+
524
  holiday1_end,
525
+
526
  holiday2_start,
527
+
528
  holiday2_end,
529
+
530
  ],
531
+
532
  outputs=[
533
+
534
  accuracy_output,
535
+
536
  actual_plot,
537
+
538
  forecast_plot,
539
+
540
  forecast_table,
541
+
542
  ],
543
+
544
  )
545
 
546
+ # =====================================================
547
  # LAUNCH
548
+ # =====================================================
549
 
550
  demo.launch()