Nehal61/Procurement_automation
0
1 2import gradio as gr3import pandas as pd4from statsmodels.tsa.arima.model import ARIMA5import warnings6 7# Suppress specific warnings related to ARIMA8warnings.filterwarnings("ignore", category=UserWarning)9warnings.filterwarnings("ignore", category=FutureWarning)10warnings.filterwarnings("ignore", category=RuntimeWarning)11 12# Function to process the CSV and perform the forecasting13def demand_forecasting(csv_file, type_value):14 # Load the CSV file15 df = pd.read_csv(csv_file.name) # .name is used to get the file path16 17 # Preprocess the data18 df.columns = df.columns.str.strip()19 for col in df.select_dtypes(include='object').columns:20 df[col] = df[col].str.strip()21 df['Date of Sale'] = pd.to_datetime(df['Date of Sale'], format='%d-%b-%y')22 23 # Filter the data based on 'Type'24 df_filtered = df[df['Type'] == type_value]25 df_filtered.set_index('Date of Sale', inplace=True)26 27 # Group and resample data by product name and month-end frequency28 monthly_sales_by_product = (29 df_filtered.groupby('Product Name')30 .resample('M')['Quantity']31 .sum()32 .reset_index()33 )34 35 # Calculate total sales by product36 Total_sales_product = df_filtered.groupby('Product Name')['Quantity'].sum().reset_index()37 38 # Create a list to store the forecasted sums for each product39 forecast_sums = []40 41 # Get a list of unique product names42 product_names = monthly_sales_by_product['Product Name'].unique()43 44 # Loop through each product and forecast sales45 for product_name in product_names:46 # Filter data for the current product47 product_data = monthly_sales_by_product[monthly_sales_by_product['Product Name'] == product_name].copy()48 49 # Ensure 'Date of Sale' is in datetime format using .loc[]50 product_data.loc[:, 'Date of Sale'] = pd.to_datetime(product_data['Date of Sale'])51 52 # Set the 'Date of Sale' as the index and ensure the index has frequency information53 product_data.set_index('Date of Sale', inplace=True)54 55 # Check if we have enough data points and set a frequency56 if len(product_data) >= 1: # Adjust based on ARIMA requirements57 product_data = product_data.asfreq('M') # Set frequency to monthly58 59 try:60 # Fit the ARIMA model61 model = ARIMA(product_data['Quantity'], order=(1, 1, 1))62 model_fit = model.fit()63 64 # Forecast for the next 4 months65 forecast_steps = 466 forecast = model_fit.forecast(steps=forecast_steps)67 68 69 # Sum the forecasted values for this product70 forecast_sum = forecast.sum()71 forecast_sum = round(forecast_sum)72 forecast_sums.append({'Product Name': product_name, 'Forecasted Quantity Sum': forecast_sum})73 74 except Exception as e:75 print(f"Could not fit ARIMA model for {product_name}: {e}")76 else:77 print(f"Not enough data points for {product_name} to fit ARIMA model.")78 79 # Create a DataFrame from the forecast sums80 forecast_summary_df = pd.DataFrame(forecast_sums)81 82 # Perform a left merge to ensure all product names from Total_sales_product are included83 combined_df = pd.merge(Total_sales_product, forecast_summary_df, on='Product Name', how='left')84 85 # Rename columns for clarity86 combined_df.columns = ['Product Name', 'Total Quantity Sold', 'Forecasted Quantity Sum']87 88 # Save the combined DataFrame to a CSV file89 output_file = 'combined_df.csv'90 combined_df.to_csv(output_file, index=False)91 92 return output_file93 94# Gradio Interface95interface = gr.Interface(96 fn=demand_forecasting,97 inputs=[98 gr.File(label="Upload CSV File"),99 gr.Textbox(label="Enter 'Type' (e.g., 'EW')")100 ],101 outputs=gr.File(label="Download Combined Data CSV")102)103 104# Launch the interface105interface.launch(share=True)106 