|
|
| import numpy as np |
| import joblib |
| import pandas as pd |
| from flask import Flask, request, jsonify |
| import os |
|
|
| APP_DIR = os.path.dirname(os.path.abspath(__file__)) |
|
|
| |
| superkart_api = Flask("superkart_predictor") |
|
|
| |
| try: |
| preprocessor_path = os.path.join(APP_DIR, "preprocessor.joblib") |
| model_path = os.path.join(APP_DIR, "model.joblib") |
|
|
| preprocessor = joblib.load(preprocessor_path) |
| model = joblib.load(model_path) |
| print("✅ Preprocessor and model loaded successfully.") |
| except Exception as e: |
| print(f"❌ Error loading artifacts: {e}") |
| preprocessor = None |
| model = None |
|
|
| |
| @superkart_api.get('/') |
| def home(): |
| return "Welcome to the SuperKart Sales Prediction API!" |
|
|
| |
| @superkart_api.post('/v1/predict') |
| def predict_sales(): |
|
|
| if preprocessor is None or model is None: |
| return jsonify({"error": "Model or preprocessor not loaded"}), 500 |
|
|
| data = request.get_json() |
|
|
| try: |
| |
| sugar_map = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2} |
| size_map = {'Small': 0, 'Medium': 1, 'High': 2} |
| city_type_map = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2} |
|
|
| |
| sample = { |
| 'Product_Weight': data['Product_Weight'], |
| 'Product_Sugar_Content': sugar_map.get(data['Product_Sugar_Content']), |
| 'Product_Allocated_Area': data['Product_Allocated_Area'], |
| 'Product_Type': data['Product_Type'], |
| 'Product_MRP': data['Product_MRP'], |
| 'Store_Size': size_map.get(data['Store_Size']), |
| 'Store_Location_City_Type': city_type_map.get(data['Store_Location_City_Type']), |
| 'Store_Type': data['Store_Type'], |
| 'Store_Age': data['Store_Age'] |
| } |
|
|
| |
| if any(v is None for v in [sample['Product_Sugar_Content'], sample['Store_Size'], sample['Store_Location_City_Type']]): |
| return jsonify({"error": "Invalid value for ordinal feature (e.g., 'Store_Size', 'Product_Sugar_Content')"}), 400 |
|
|
| except KeyError as e: |
| return jsonify({"error": f"Missing key in JSON payload: {e}"}), 400 |
| except Exception as e: |
| return jsonify({"error": f"Error processing input: {str(e)}"}), 400 |
|
|
| |
| input_data = pd.DataFrame([sample]) |
|
|
| |
| try: |
| |
| processed_data = preprocessor.transform(input_data) |
|
|
| |
| prediction = model.predict(processed_data).tolist()[0] |
|
|
| return jsonify({'predicted_sales': round(prediction, 2)}) |
|
|
| except Exception as e: |
| return jsonify({"error": f"Error during prediction: {str(e)}"}), 500 |
|
|
| |
| if __name__ == '__main__': |
| |
| superkart_api.run(host='0.0.0.0', port=7860, debug=True) |
|
|