Lokiiparihar commited on
Commit
0fa1c54
·
verified ·
1 Parent(s): 099d2ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -14
app.py CHANGED
@@ -1,21 +1,69 @@
1
- import flask
2
- from flask import Flask, request, jsonify
3
  import joblib
4
  import pandas as pd
5
- import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- app = Flask(__name__)
8
 
9
- model = joblib.load("superkart_model.joblib")
10
 
11
- @app.route("/")
12
- def health():
13
- return "OK"
 
14
 
15
- @app.route("/v1/predict", methods=["POST"])
16
- def predict():
17
- data = request.get_json()
18
- df = pd.DataFrame([data])
19
- return jsonify({"Sales": model.predict(df).tolist()[0]})
20
 
21
- app.run(host="0.0.0.0", port=7860)
 
 
 
1
+ # Import necessary libraries
2
+ import os
3
  import joblib
4
  import pandas as pd
5
+ from flask import Flask, request, jsonify
6
+
7
+ # Initialize Flask app
8
+ superkart_api = Flask("SuperKart")
9
+
10
+ # Global model variable (lazy loading)
11
+ model = None
12
+ MODEL_PATH = "superkart_model.joblib"
13
+
14
+
15
+ def load_model():
16
+ """
17
+ Load the model only once when first needed.
18
+ Prevents Hugging Face startup crashes.
19
+ """
20
+ global model
21
+ if model is None:
22
+ if not os.path.exists(MODEL_PATH):
23
+ raise FileNotFoundError(f"Model file not found: {MODEL_PATH}")
24
+ model = joblib.load(MODEL_PATH)
25
+
26
+
27
+ # Health check endpoint (IMPORTANT for Hugging Face Spaces)
28
+ @superkart_api.get("/")
29
+ def home():
30
+ return "SuperKart API is running"
31
+
32
+
33
+ # Prediction endpoint
34
+ @superkart_api.post("/v1/predict")
35
+ def predict_sales():
36
+ try:
37
+ load_model()
38
+
39
+ data = request.get_json(force=True)
40
+
41
+ # Enforce correct feature schema
42
+ sample = {
43
+ "Product_Weight": data["Product_Weight"],
44
+ "Product_Sugar_Content": data["Product_Sugar_Content"],
45
+ "Product_Allocated_Area": data["Product_Allocated_Area"],
46
+ "Product_MRP": data["Product_MRP"],
47
+ "Store_Size": data["Store_Size"],
48
+ "Store_Location_City_Type": data["Store_Location_City_Type"],
49
+ "Store_Type": data["Store_Type"],
50
+ "Product_Id_char": data["Product_Id_char"],
51
+ "Store_Age_Years": data["Store_Age_Years"],
52
+ "Product_Type_Category": data["Product_Type_Category"],
53
+ }
54
+
55
+ input_df = pd.DataFrame([sample])
56
 
57
+ prediction = model.predict(input_df)[0]
58
 
59
+ return jsonify({"Sales": float(prediction)})
60
 
61
+ except KeyError as e:
62
+ return jsonify({"error": f"Missing field: {str(e)}"}), 400
63
+ except Exception as e:
64
+ return jsonify({"error": str(e)}), 500
65
 
 
 
 
 
 
66
 
67
+ # Run app (Hugging Face requires port 7860)
68
+ if __name__ == "__main__":
69
+ superkart_api.run(host="0.0.0.0", port=7860)