import joblib import pandas as pd from flask import Flask, request, jsonify import numpy as np # Initialize Flask app with a name app = Flask("SuperKart sales prediction app backend") # Load the trained churn prediction model model = joblib.load("SuperKart_model_deployment_model_v1_0.joblib") # Define a route for the home page @app.get('/') def home(): return "Welcome to the SuperKart Sales Prediction API" # Define an endpoint to predict sales of the single product in a store @app.post('/v1/sales') def predict_sales(): # Get JSON data from the request store_data = request.get_json() # Extract relevant store features from the input data requestData = { 'Product_Weight': store_data['Product_Weight'], 'Product_Sugar_Content': store_data['Product_Sugar_Content'], 'Product_Allocated_Area': store_data['Product_Allocated_Area'], 'Product_Type': store_data['Product_Type'], 'Product_MRP': store_data['Product_MRP'], 'Store_Id': store_data['Store_Id'], 'Store_Establishment_Year': store_data['Store_Establishment_Year'], 'Store_Size': store_data['Store_Size'], 'Store_Location_City_Type': store_data['Store_Location_City_Type'], 'Store_Type': store_data['Store_Type'] } # Convert the extracted data into a DataFrame input_data = pd.DataFrame([requestData]) # create encoder with OneHotEncoder for encoding the selected values to match the training data # encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False) # Important for handling unseen categories # You MUST use the *trained* encoder to transform the new data # encoded_new_data = encoder.transform(input_data[['Product_Sugar_Content','Product_Type','Store_Id','Store_Size','Store_Location_City_Type','Store_Type']]) #encoded_new_data = pd.get_dummies( # input_data, # columns=['Product_Sugar_Content','Product_Type','Store_Id','Store_Size','Store_Location_City_Type','Store_Type'], # drop_first=True, #); #print("The data entered are below") #print(encoded_new_data) # Make a Sales prediction using the trained model prediction = model.predict(input_data).tolist()[0] #Calculate the actual price predicted_sales = np.exp(prediction) # Convert predicted_price to Python float predicted_sales = round(float(predicted_sales), 2) # Return the prediction as a JSON response return jsonify({'Predicted_Sale': predicted_sales})