| import flask |
| from flask import Flask, request, jsonify |
| import joblib |
| import pandas as pd |
| import numpy as np |
| import sys |
|
|
| print('Starting Superkart Sales Predictor Flask app...', file=sys.stdout) |
|
|
| |
| app = Flask("Superkart Sales Predictor") |
| print('Flask app instantiated.', file=sys.stdout) |
|
|
| |
| print('Attempting to load model...', file=sys.stdout) |
| loaded_model = joblib.load('best_rf_model.joblib') |
| print('Model loaded successfully!', file=sys.stdout) |
|
|
| |
| |
| expected_features_list = ['Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area', |
| 'Product_Type', 'Product_MRP', 'Store_Size', |
| 'Store_Location_City_Type', 'Store_Type', 'yr_since_store_estab'] |
|
|
| |
| @app.route('/predict', methods=['POST']) |
| def predict(): |
| print('Prediction request received.', file=sys.stdout) |
| try: |
| |
| print('Attempting to get JSON data from request...', file=sys.stdout) |
| data = request.get_json(force=True) |
| print(f'Received data: {data}', file=sys.stdout) |
|
|
| |
| if isinstance(data, dict): |
| input_df = pd.DataFrame([data]) |
| elif isinstance(data, list): |
| input_df = pd.DataFrame(data) |
| else: |
| print('Invalid input data format.', file=sys.stdout) |
| return jsonify({'error': 'Invalid input data format, expected dict or list of dicts'}), 400 |
|
|
| |
| |
| print('Reindexing input DataFrame and converting dtypes...', file=sys.stdout) |
| input_df = input_df.reindex(columns=expected_features_list, fill_value=np.nan) |
|
|
| |
| |
| categorical_cols_expected = ['Product_Sugar_Content', 'Product_Type', 'Store_Size', |
| 'Store_Location_City_Type', 'Store_Type'] |
|
|
| for col in categorical_cols_expected: |
| if col in input_df.columns: |
| input_df[col] = input_df[col].astype('category') |
| else: |
| |
| pass |
| print('Input DataFrame prepared for prediction.', file=sys.stdout) |
|
|
| |
| print('Making prediction...', file=sys.stdout) |
| predictions = loaded_model.predict(input_df) |
| print('Prediction successful.', file=sys.stdout) |
|
|
| |
| return jsonify(predictions.tolist()) |
|
|
| except Exception as e: |
| print(f'Error during prediction: {str(e)}', file=sys.stderr) |
| return jsonify({'error': str(e)}), 500 |
|
|
| |
| |
| |
|
|