File size: 3,866 Bytes
0c2dc69
 
 
 
 
 
 
 
 
 
ba9e3d0
0c2dc69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba9e3d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c2dc69
 
 
 
 
 
 
 
 
 
 
 
 
 
ba9e3d0
0c2dc69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba9e3d0
0c2dc69
 
 
 
 
 
 
 
 
 
 
 
 
 
402242c
0c2dc69
402242c
ba9e3d0
 
0c2dc69
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import gradio as gr
import warnings
import pandas as pd;
import numpy as np;
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
from sklearn.metrics import mean_absolute_error, mean_squared_error
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from openpyxl.utils import get_column_letter
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from pandas import DataFrame

from datetime import datetime

def forecast(name,duration):
  df = pd.read_csv(name)
  df['Date'] = pd.to_datetime(df['Date'])
  df.set_index('Date', inplace=True)
  model = ExponentialSmoothing(df, trend='add', seasonal='add', seasonal_periods=48)
  model_fit = model.fit()
  freq = 'W'
  steps = 7
  if duration == 'Month':
    steps = 30
    freq = 'M'

  forecast = model_fit.forecast(steps=steps)
  last_date = df.index[-1]
  future_dates = pd.date_range(start=last_date + pd.DateOffset(months=1), periods=steps, freq=freq)
  forecast_df = pd.DataFrame({
      'Date': future_dates,
      'No. of Vehicles': forecast
  })
  return forecast_df

def changewidth(worksheet):
    column_widths = {}
    
    # Calculate the maximum width for each column
    for column in worksheet.columns:
        column_letter = get_column_letter(column[0].column)
        max_length = 0
        for cell in column:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except TypeError:
                pass
        column_widths[column_letter] = max_length

    # Set the column widths based on the maximum width for each column
    for column_letter, width in column_widths.items():
        column_width = (width + 2) * 1.2  # Adjust the width by adding some padding
        worksheet.column_dimensions[column_letter].width = column_width

    return worksheet


warnings.filterwarnings('ignore')
def predict(operation,file):
  if file == None:
    return None,"No file inputted"

  try:
    algos = dict()
    predicted = forecast(file.name,operation)
    algos['SARIMA'] = predicted
    algos['Exponential Smoothing'] = predicted
    algos['XGBoost'] = predicted

    # output_name = "Forecasted.csv"
    # predicted.to_csv(output_name,index=False)

    workbook = Workbook()
    # Remove the default sheet
    default_sheet = workbook.active
    workbook.remove(default_sheet)

    for aname in algos:
      plt.figure(figsize=(10, 5))
      plt.plot(algos[aname]['Date'], algos[aname]['No. of Vehicles'])
      plt.xlabel('Date')
      plt.ylabel('No. of Vehicles')
      plt.title('Vehicle Count over Time')
      # Save the plot as an image file (e.g., PNG)
      plot_filename = 'line_plot.png'
      plt.savefig(plot_filename)
      # Create a new sheet for the current DataFrame
      worksheet = workbook.create_sheet(title=aname)
      # Write the DataFrame to the Excel file
      for index, row in algos[aname].iterrows():
        worksheet.append(row.tolist())
      # Insert the plot image into the Excel file
      img = Image(plot_filename)
      worksheet.add_image(img, 'D1')
      worksheet = changewidth(worksheet)
    # Save the Excel file
    now = datetime.now()
    formatted_datetime = now.strftime("%H:%M %d-%m-%Y")
    output_filename = 'forecast' + formatted_datetime + '.xlsx'
    workbook.save(output_filename)

  except Exception as e:
    return None,str(e)

  return output_filename,"Successfully predicted "+operation+" ahead"


iface = gr.Interface(fn=predict,
                     
                     inputs=[gr.Radio(label='Predict ahead:',choices=['Month','Week'],value='Month'),gr.File(label="Input file")],

                     outputs=[gr.File(label="Output file"),gr.Textbox(label='Log',interactive=False)],

                     debug=True)
iface.launch()