Spaces:
Sleeping
Sleeping
| # backend_files/app.py | |
| from flask import Flask, request, jsonify | |
| import joblib | |
| import pandas as pd | |
| import os | |
| import datetime | |
| app = Flask(__name__) | |
| # Load model | |
| #model = joblib.load('random_forest_best_model.pkl') | |
| model = joblib.load('bagging_best_model.pkl') | |
| def home(): | |
| return "SuperKart Sales Forecasting API" | |
| # @app.route('/predict', methods=['POST']) | |
| # def predict(): | |
| # try: | |
| # data = request.json | |
| # features = [ | |
| # 'Product_Id', 'Product_Weight', 'Product_Sugar_Content', | |
| # 'Product_Allocated_Area', 'Product_Type', 'Product_MRP', | |
| # 'Store_Id', 'Store_Establishment_Year', 'Store_Size', | |
| # 'Store_Location_City_Type', 'Store_Type' | |
| # ] | |
| # df = pd.DataFrame([data], columns=features) | |
| # prediction = model.predict(df) | |
| # return jsonify({'prediction': float(prediction[0])}) | |
| # except Exception as e: | |
| # return jsonify({'error': str(e)}), 400 | |
| def predict(): | |
| try: | |
| # Parse incoming JSON | |
| data = request.get_json() | |
| # Convert to DataFrame | |
| input_df = pd.DataFrame([data]) | |
| # Calculate Store_Age | |
| current_year = datetime.datetime.now().year | |
| if 'Store_Establishment_Year' in input_df.columns: | |
| input_df['Store_Age'] = current_year - input_df['Store_Establishment_Year'] | |
| input_df.drop('Store_Establishment_Year', axis=1, inplace=True) | |
| else: | |
| return jsonify({"error": "Missing 'Store_Establishment_Year'"}), 400 | |
| # Predict | |
| prediction = model.predict(input_df) | |
| return jsonify({"prediction": round(prediction[0], 2)}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 400 | |
| if __name__ == '__main__': | |
| #port = int(os.environ.get('PORT', 5000)) | |
| port = int(os.environ.get('PORT', 7860)) | |
| app.run(host='0.0.0.0', port=port) |