Ansh91 commited on
Commit
d944941
Β·
1 Parent(s): b087eef

πŸš€ Rebuilt backend with Flask + Docker

Browse files
Files changed (1) hide show
  1. app.py +55 -10
app.py CHANGED
@@ -1,23 +1,68 @@
 
1
 
2
  from flask import Flask, request, jsonify
3
  import pandas as pd
4
  import numpy as np
5
  import joblib
6
  import os
 
7
 
8
  app = Flask(__name__)
9
- model = joblib.load("best_model.pkl")
10
 
 
 
 
 
 
 
 
 
 
 
 
11
  @app.route("/", methods=["GET"])
12
  def health_check():
13
- return "βœ… SuperKart backend is up!", 200
14
 
 
15
  @app.route("/v1/forecast", methods=["POST"])
16
- def predict():
17
- data = request.get_json()
18
- df = pd.DataFrame([data])
19
- df["Store_Age"] = 2025 - df["Store_Establishment_Year"]
20
- df["Price_per_kg"] = df["Product_MRP"] / df["Product_Weight"]
21
- df["MRP_Band"] = pd.qcut(df["Product_MRP"], 3, labels=["Low", "Mid", "High"])
22
- pred = np.expm1(model.predict(df)[0])
23
- return jsonify({"Predicted_Sales": round(float(pred), 2)}), 200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SuperKart - Sales Forecasting Flask API
2
 
3
  from flask import Flask, request, jsonify
4
  import pandas as pd
5
  import numpy as np
6
  import joblib
7
  import os
8
+ import traceback
9
 
10
  app = Flask(__name__)
 
11
 
12
+ # === Load Trained Model ===
13
+ MODEL_PATH = "best_model.pkl"
14
+
15
+ try:
16
+ model = joblib.load(MODEL_PATH)
17
+ print("βœ… Model loaded successfully.")
18
+ except Exception as e:
19
+ print("❌ Failed to load model from:", MODEL_PATH)
20
+ traceback.print_exc()
21
+
22
+ # === Health Check ===
23
  @app.route("/", methods=["GET"])
24
  def health_check():
25
+ return "βœ… SuperKart backend is up and running!", 200
26
 
27
+ # === Single Forecast Prediction ===
28
  @app.route("/v1/forecast", methods=["POST"])
29
+ def predict_single():
30
+ try:
31
+ data = request.get_json()
32
+ df = pd.DataFrame([data])
33
+
34
+ df["Store_Age"] = 2025 - df["Store_Establishment_Year"]
35
+ df["Price_per_kg"] = df["Product_MRP"] / df["Product_Weight"]
36
+ df["MRP_Band"] = pd.cut(df["Product_MRP"], bins=[0, 100, 200, float("inf")], labels=["Low", "Mid", "High"])
37
+
38
+ pred_log = model.predict(df)[0]
39
+ pred = np.expm1(pred_log)
40
+
41
+ return jsonify({"Predicted_Sales": round(float(pred), 2)}), 200
42
+ except Exception as e:
43
+ return jsonify({"error": str(e)}), 500
44
+
45
+ # === Batch Forecast Prediction ===
46
+ @app.route("/v1/forecastbatch", methods=["POST"])
47
+ def predict_batch():
48
+ try:
49
+ file = request.files.get("file")
50
+ if file is None:
51
+ return jsonify({"error": "No file uploaded"}), 400
52
+
53
+ df = pd.read_csv(file)
54
+ df["Store_Age"] = 2025 - df["Store_Establishment_Year"]
55
+ df["Price_per_kg"] = df["Product_MRP"] / df["Product_Weight"]
56
+ df["MRP_Band"] = pd.cut(df["Product_MRP"], bins=[0, 100, 200, float("inf")], labels=["Low", "Mid", "High"])
57
+
58
+ preds = model.predict(df)
59
+ results = [round(float(np.expm1(p)), 2) for p in preds]
60
+
61
+ return jsonify({"Predictions": results}), 200
62
+ except Exception as e:
63
+ return jsonify({"error": str(e)}), 500
64
+
65
+ # === Entrypoint for Docker / HF Space ===
66
+ if __name__ == "__main__":
67
+ port = int(os.environ.get("PORT", 7860))
68
+ app.run(host="0.0.0.0", port=port)