Backend / app.py
AnkushWaghmare's picture
Update app.py
adbe0f2 verified
import joblib
import pandas as pd
from flask import Flask, request, jsonify
# Initialize Flask app
app = Flask("Sales Forecasting")
# Load the trained Sales Forecasting prediction model
model = joblib.load("sales_forecasting_model_v1_0.joblib")
# Define categorical mapping dictionary
replaceStruct = {
"Product_Sugar_Content": {"Low Sugar": 1, "Regular": 2, "No Sugar": 3, "reg": 4},
"Product_Type": {
"Fruits and Vegetables": 1, "Snack Foods": 2, "Frozen Foods": 3, "Dairy": 4,
"Household": 5, "Baking Goods": 6, "Canned": 7, "Health and Hygiene": 8,
"Meat": 9, "Soft Drinks": 10, "Bread": 11, "Breads": 12, "Hard Drinks": 13,
"Others": 14, "Starchy Foods": 15, "Breakfast": 16, "Seafood": 17
},
"Store_Id": {"OUT001": 1, "OUT002": 2, "OUT003": 3, "OUT004": 4},
"Store_Size": {"Medium": 1, "High": 2, "Low": 3, "Small": 4},
"Store_Location_City_Type": {"Tier 1": 1, "Tier 2": 2, "Tier 3": 3},
"Store_Type": {"Departmental Store": 1, "Supermarket Type1": 2, "Supermarket Type2": 3, "Food Mart": 4},
}
# Home route
@app.get('/')
def home():
return "Welcome to the Sales Forecasting API!"
# Prediction endpoint
@app.post('/v1/sales_forecast')
def predict_sales():
# Get JSON data from the request
user_data = request.get_json()
# Extract relevant customer features from the input data
sample = {
"Product_Weight": user_data["Product_Weight"],
"Product_Sugar_Content": user_data["Product_Sugar_Content"],
"Product_Allocated_Area": user_data["Product_Allocated_Area"],
"Product_Type": user_data["Product_Type"],
"Product_MRP": user_data["Product_MRP"],
"Store_Size": user_data["Store_Size"],
"Store_Age": user_data.get("Store_Age", 10)
}
# Convert to DataFrame and apply mapping
input_data = pd.DataFrame([sample]).replace(replaceStruct)
# Make a Sales Forecasting prediction
prediction = model.predict(input_data)[0]
# Prepare readable response
prediction_label = f"Prediction of Weekly Sales is {prediction:.2f}"
# Return JSON
return jsonify({'Prediction': prediction_label})
# Run the Flask app in debug mode
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7860, debug=True)