Backend / app.py
jarpan03's picture
Upload folder using huggingface_hub
c096607 verified
import joblib
import pandas as pd
from flask import Flask, request, jsonify
from datetime import datetime
# Initialize Flask app
super_kart_api = Flask("Super Kart Product Sales Predictor")
# Load the trained model
model = joblib.load("super_kart_model_v1_0.joblib")
# Define a route for the home page
@super_kart_api.get('/')
def home():
return "Welcome to the Super Kart Product Sales Prediction API!"
# Define an endpoint to predict price for a single product
@super_kart_api.post('/v1/product')
def predict_product_sales_price():
# Get JSON data from the request
product_data = request.get_json()
current_year = datetime.now().year
# Extract relevant product features from the input data
sample = {
'Product_Weight': product_data['Product_Weight'],
'Product_Sugar_Content': product_data['Product_Sugar_Content'],
'Product_Type': product_data['Product_Type'],
'Product_MRP': product_data['Product_MRP'],
'Store_Id': product_data['Store_Id'],
'Store_Size': product_data['Store_Size'],
'Store_Location_City_Type': product_data['Store_Location_City_Type'],
'Store_Type': product_data['Store_Type'],
'Store_Age': int(current_year - product_data['Store_Establishment_Year'])
}
# Convert the extracted data into a DataFrame
input_data = pd.DataFrame([sample])
# Make a prediction using the trained model
prediction = model.predict(input_data).tolist()[0]
# Return the prediction as a JSON response
return jsonify({'Predicted_Product_Sales': prediction})
# Define an endpoint to predict product sales price for a batch of product
@super_kart_api.post('/v1/productbatch')
def predict_product_batch():
# Get the uploaded CSV file from the request
file = request.files['file']
# Read the file into a DataFrame
data = pd.read_csv(file)
current_year = datetime.now().year
input_data = data.copy()
input_data['Store_Establishment_Year'] = pd.to_numeric(input_data['Store_Establishment_Year'], errors='coerce')
input_data['Store_Age'] = current_year - input_data['Store_Establishment_Year']
input_data = input_data.drop(['Product_Id','Store_Establishment_Year','Product_Allocated_Area'],axis=1)
#Data Cleaning
input_data["Product_Sugar_Content"] = input_data["Product_Sugar_Content"].replace("reg", "Regular")
# Make predictions for the batch data
predictions = model.predict(input_data).tolist()
# Add predictions to the DataFrame
data['Predicted_Product_Sales'] = predictions
# Convert results to dictionary
result = data.to_dict(orient="records")
return jsonify(result)
# Run the Flask app in debug mode
if __name__ == '__main__':
super_kart_api.run(debug=True)