Spaces:
Sleeping
Sleeping
| # Import necessary libraries | |
| import numpy as np | |
| import joblib # For loading the serialized model | |
| import pandas as pd # For data manipulation | |
| from flask import Flask, request, jsonify # For creating the Flask API | |
| from flask_cors import CORS | |
| # Initialize the Flask application | |
| superkart_api = Flask("SuperKart Revenue Predictor") | |
| CORS(superkart_api) | |
| #model path needs to be updated to root once this is pushed | |
| model_path = "deployment_files/Backend/SuperKart_Model_V1_0.joblib" | |
| # Load the trained machine learning model | |
| model = joblib.load("model_path") | |
| # Health check route | |
| def home(): | |
| return "Welcome to SuperKart Sales Prediction" | |
| # Prediction route | |
| def predict_sales(): | |
| try: | |
| # Parse JSON payload | |
| data = request.get_json() | |
| print("Raw incoming data:", data) | |
| # Validate expected fields | |
| required_fields = [ | |
| 'Product_Weight', | |
| 'Product_Sugar_Content', | |
| 'Product_Allocated_Area', | |
| 'Product_MRP', | |
| 'Store_Size', | |
| 'Store_Location_City_Type', | |
| 'Store_Type', | |
| 'Store_Age_Years', | |
| 'Product_Type_Category' | |
| ] | |
| missing_fields = [f for f in required_fields if f not in data] | |
| if missing_fields: | |
| return jsonify({'error': f"Missing fields: {missing_fields}"}), 400 | |
| # Convert and transform input | |
| sample = { | |
| 'Product_Weight': float(data['Product_Weight']), | |
| 'Product_Sugar_Content': data['Product_Sugar_Content'], | |
| 'Product_Allocated_Area_Log': np.log1p(float(data['Product_Allocated_Area'])), # log-transform | |
| 'Product_MRP': float(data['Product_MRP']), | |
| 'Store_Size': data['Store_Size'], | |
| 'Store_Location_City_Type': data['Store_Location_City_Type'], | |
| 'Store_Type': data['Store_Type'], | |
| 'Store_Age_Years': int(data['Store_Age_Years']), | |
| 'Product_Type_Category': data['Product_Type_Category'] | |
| } | |
| input_df = pd.DataFrame([sample]) | |
| print("Transformed input for model:\n", input_df) | |
| # Make prediction | |
| prediction = model.predict(input_df).tolist()[0] | |
| return jsonify({'Predicted_Sales': prediction}) | |
| except Exception as e: | |
| print("Error during prediction:", str(e)) | |
| return jsonify({'error': f"Prediction failed: {str(e)}"}), 500 | |
| # Run the app (for local testing only) | |
| if __name__ == '__main__': | |
| superkart_api.run(debug=True) | |