aibtus commited on
Commit
284b571
·
verified ·
1 Parent(s): 107de75

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +27 -85
app.py CHANGED
@@ -1,97 +1,39 @@
1
  # app.py — SuperKart Sales Forecaster Backend
2
 
3
- # ---------------------------------------------------------
4
- # Flask App Setup
5
- # ---------------------------------------------------------
6
- app = Flask(__name__)
7
- app.name = "SuperKart Sales Forecaster"
8
-
9
- # ---------------------------------------------------------
10
- # Model Files (relative paths inside Docker)
11
- # ---------------------------------------------------------
12
- MODEL_PKL = os.path.join("backend_files", "tuned_xgb_sales_forecaster.pkl")
13
- MODEL_JSON = os.path.join("backend_files", "tuned_xgb_sales_forecaster.json")
14
-
15
- # ---------------------------------------------------------
16
- # Feature Columns expected by the model pipeline
17
- # ---------------------------------------------------------
18
- FEATURE_COLS = [
19
- 'Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area',
20
- 'Product_Type', 'Product_MRP', 'Store_Size',
21
- 'Store_Location_City_Type', 'Store_Type', 'Store_Age',
22
- 'Product_Category_Simplified'
23
- ]
24
 
25
- # ---------------------------------------------------------
26
- # Load the Serialized Model on Startup
27
- # ---------------------------------------------------------
28
- model_pipeline = None
29
 
30
- try:
31
- if os.path.exists(MODEL_PKL):
32
- model_pipeline = joblib.load(MODEL_PKL)
33
- print(f"Model pipeline loaded successfully from {MODEL_PKL}")
34
- elif os.path.exists(MODEL_JSON):
35
- xgb_model = XGBRegressor()
36
- xgb_model.load_model(MODEL_JSON)
37
- model_pipeline = xgb_model
38
- print(f"XGBoost model loaded from {MODEL_JSON}")
39
- else:
40
- raise FileNotFoundError("No model file found in backend_files/")
41
- except Exception as e:
42
- print(f"CRITICAL ERROR: Unable to load model → {e}")
43
 
44
- # ---------------------------------------------------------
45
- # Root Route (Required by Hugging Face Spaces)
46
- # ---------------------------------------------------------
47
- @app.route("/", methods=["GET"])
48
  def home():
49
- return jsonify({
50
- "message": f"Welcome to {app.name}! 🚀",
51
- "available_endpoints": ["/health", "/predict"],
52
- "status": "running"
53
- })
54
-
55
- # ---------------------------------------------------------
56
- # Health Check Endpoint (for Docker + Hugging Face)
57
- # ---------------------------------------------------------
58
- @app.route("/health", methods=["GET"])
59
- def health_check():
60
- status = "healthy" if model_pipeline is not None else "model_not_loaded"
61
- return jsonify({"app": app.name, "status": status}), 200 if model_pipeline else 500
62
-
63
- # ---------------------------------------------------------
64
- # Prediction Endpoint
65
- # ---------------------------------------------------------
66
- @app.route('/predict', methods=['POST'])
67
- def predict_sales():
68
- if model_pipeline is None:
69
- return jsonify({'error': 'Model not loaded on server.'}), 500
70
 
 
 
71
  try:
72
- data = request.get_json(force=True)
73
-
74
- if not isinstance(data, list) or len(data) == 0:
75
- return jsonify({'error': 'Input data must be a non-empty list of objects.'}), 400
76
-
77
- input_df = pd.DataFrame(data, columns=FEATURE_COLS)
78
-
79
- log_prediction = model_pipeline.predict(input_df)
80
- predicted_sales = np.expm1(log_prediction)
81
-
82
  return jsonify({
83
- "status": "success",
84
- "predicted_sales_revenue": round(float(predicted_sales[0]), 2)
85
  })
86
-
87
  except Exception as e:
88
- print(f"Prediction error: {e}")
89
- return jsonify({'error': f'Prediction failed: {str(e)}'}), 400
 
 
90
 
91
- # ---------------------------------------------------------
92
- # Docker Entrypoint
93
- # ---------------------------------------------------------
94
- if __name__ == '__main__':
95
- port = int(os.environ.get("PORT", 7860)) # Hugging Face uses 7860
96
- print(f"Starting {app.name} on port {port} ...")
97
- app.run(host='0.0.0.0', port=port)
 
1
  # app.py — SuperKart Sales Forecaster Backend
2
 
3
+ from flask import Flask, request, jsonify
4
+ import joblib
5
+ import numpy as np
6
+ import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Initialize Flask app
9
+ app = Flask(__name__)
 
 
10
 
11
+ # === Load model ===
12
+ model = joblib.load("tuned_xgb_sales_forecaster.pkl")
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ @app.route("/")
 
 
 
15
  def home():
16
+ return jsonify({"message": "SuperKart Sales Forecasting API is running!"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ @app.route("/predict", methods=["POST"])
19
+ def predict():
20
  try:
21
+ # Expecting JSON input with "features" list
22
+ data = request.get_json()
23
+ features = np.array(data["features"]).reshape(1, -1)
24
+
25
+ prediction_log = model.predict(features)[0]
26
+ prediction_original = float(np.expm1(prediction_log))
27
+
 
 
 
28
  return jsonify({
29
+ "predicted_sales": prediction_original,
30
+ "status": "success"
31
  })
 
32
  except Exception as e:
33
+ return jsonify({
34
+ "error": str(e),
35
+ "status": "failed"
36
+ }), 400
37
 
38
+ if __name__ == "__main__":
39
+ app.run(host="0.0.0.0", port=7860)