Download app.py from XPMaster/manafeth: direct link, hf CLI and curl.
- Browser
- Download file 3.87 kB
-
https://huggingface.co/spaces/XPMaster/manafeth/resolve/main/app.py
- Command line
-
hf download hf://spaces/XPMaster/manafeth/app.py
-
curl -L -o app.py https://huggingface.co/spaces/XPMaster/manafeth/resolve/main/app.py
3.87 kB
| 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() |