Lokiiparihar commited on
Commit
b569e15
·
verified ·
1 Parent(s): ca557a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -34
app.py CHANGED
@@ -1,62 +1,66 @@
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_v1_0.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
@@ -64,6 +68,6 @@ def predict_sales():
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)
 
 
1
  import os
2
  import joblib
3
  import pandas as pd
4
  from flask import Flask, request, jsonify
5
 
6
  # Initialize Flask app
7
+ app = Flask("SuperKart")
8
 
9
+ MODEL_PATH = "superkart_model.joblib"
10
  model = None
 
11
 
12
 
13
  def load_model():
 
 
 
 
14
  global model
15
  if model is None:
16
  if not os.path.exists(MODEL_PATH):
17
+ raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
18
  model = joblib.load(MODEL_PATH)
19
 
20
 
21
+ # Health check (required by Hugging Face Spaces)
22
+ @app.route("/", methods=["GET"])
23
+ def health():
24
+ return "SuperKart Backend is running"
25
 
26
 
27
+ # Prediction endpoint (MATCHES STREAMLIT)
28
+ @app.route("/predict", methods=["POST"])
29
+ def predict():
30
  try:
31
  load_model()
32
 
33
  data = request.get_json(force=True)
34
 
35
+ # Convert incoming list-based JSON to DataFrame
36
+ df = pd.DataFrame(data)
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ # -------------------------------
39
+ # FEATURE ENGINEERING (IMPORTANT)
40
+ # -------------------------------
41
 
42
+ # Store_Age_Years = 2025 - Store_Establishment_Year
43
+ if "Store_Establishment_Year" in df.columns:
44
+ df["Store_Age_Years"] = 2025 - df["Store_Establishment_Year"]
45
+ df.drop(columns=["Store_Establishment_Year"], inplace=True)
46
 
47
+ # Product_Id_char (dummy but required by model)
48
+ if "Product_Id_char" not in df.columns:
49
+ df["Product_Id_char"] = "A"
50
+
51
+ # Product_Type_Category (same as Product_Type)
52
+ if "Product_Type" in df.columns:
53
+ df["Product_Type_Category"] = df["Product_Type"]
54
+ df.drop(columns=["Product_Type"], inplace=True)
55
+
56
+ # -------------------------------
57
+ # PREDICTION
58
+ # -------------------------------
59
+ prediction = model.predict(df)
60
+
61
+ return jsonify({
62
+ "predictions": prediction.tolist()
63
+ })
64
 
65
  except KeyError as e:
66
  return jsonify({"error": f"Missing field: {str(e)}"}), 400
 
68
  return jsonify({"error": str(e)}), 500
69
 
70
 
71
+ # Run on Hugging Face required port
72
  if __name__ == "__main__":
73
+ app.run(host="0.0.0.0", port=7860)