Backend / superKartApi.py
laxmikantdeshpande's picture
Upload folder using huggingface_hub
375a372 verified
import joblib
import pandas as pd
import xgboost as xgb
from xgboost import XGBRegressor
from flask import Flask, request, jsonify
# Initialize Flask app with a name
superKartApi = Flask("Super Kart Sales Predictor")
# Load the trained churn prediction model
model = joblib.load("superkart_prediction_model_v1_0.joblib")
# Define a route for the home page
@superKartApi.get('/')
def home():
return "Welcome to the Superkart Sales Forecast API"
# Define an endpoint to predict churn for a single customer
@superKartApi.post('/v1/product')
def predict_forecast():
"""
This function handles POST requests to the '/v1/product' endpoint.
It expects a JSON payload containing property details and returns
the predicted rental price as a JSON response.
"""
# Get JSON data from the request
superKar_data = request.get_json()
# Extract relevant customer features from the input data
sample = {
'ProductWeight': superKar_data['ProductWeight'],
'ProductSugarContent': superKar_data['ProductSugarContent'],
'ProductAllocatedArea': superKar_data['ProductAllocatedArea'],
'ProductType': superKar_data['ProductType'],
'ProductMRP': superKar_data['ProductMRP'],
'StoreId': superKar_data['StoreId'],
'StoreEstablishmentYear': superKar_data['StoreEstablishmentYear'],
'StoreSize': superKar_data['StoreSize'],
'StoreLocationCityType': superKar_data['StoreLocationCityType'],
'StoreType': superKar_data['StoreType']
}
# Convert the extracted data into a DataFrame
input_data = pd.DataFrame([sample])
# Make a churn prediction using the trained model
predicted_sales_value = model.predict(input_data).tolist()[0]
# Calculate actual price
predicted_sales = np.exp(predicted_sales_value)
# Convert predicted_price to Python float
predicted_sales = round(float(predicted_sales), 2)
# Return the actual price
return jsonify({'Predicted Sales': predicted_sales})
# # Map prediction result to a human-readable label
# prediction_label = "churn" if prediction == 1 else "not churn"
# # Return the prediction as a JSON response
# return jsonify({'Prediction': prediction_label})
# Define an endpoint to predict churn for a batch of customers
@superKartApi.post('/v1/superKartbatch')
def predict_churn_batch():
"""
This function handles POST requests to the '/v1/superKartbatch' endpoint.
It expects a CSV file containing property details for multiple properties
and returns the predicted rental prices as a dictionary in the JSON response.
"""
# Get the uploaded CSV file from the request
file = request.files['file']
# Read the file into a DataFrame
input_data = pd.read_csv(file)
# Make predictions for all properties in the DataFrame (get log_sales)
predicted_log_sales = model.predict(input_data).tolist()
# Calculate actual sales
predicted_sales = [round(float(np.exp(log_price)), 2) for log_price in predicted_log_sales]
# # Make predictions for the batch data and convert raw predictions into a readable format
# predictions = [
# 'Churn' if x == 1
# else "Not Churn"
# for x in model.predict(input_data.drop("ProductId",axis=1)).tolist()
# ]
# Create a dictionary of predictions with property IDs as keys
product_id_list = input_data.ProductId.values.tolist()
output_dict = dict(zip(product_id_list, predicted_sales))
# Return the predictions dictionary as a JSON response
return output_dict