Rizwan9 commited on
Commit
accb57d
Β·
verified Β·
1 Parent(s): c3ce2bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +4 -37
app.py CHANGED
@@ -4,42 +4,28 @@ import pandas as pd
4
  import numpy as np
5
  import traceback
6
 
7
- # ── 1) CONFIG ──────────────────────────────────────────────────────────────────
8
- # Must match the file you uploaded to the Space
9
- BUNDLE_FILENAME = "best_model_random_forest.joblib"
10
 
11
- # ── 2) LOAD MODEL BUNDLE ───────────────────────────────────────────────────────
12
- # Expected bundle format: {"model": fitted_pipeline_or_model, "feature_cols": [...]}
13
  try:
14
  bundle = joblib.load(BUNDLE_FILENAME)
15
  model = bundle["model"]
16
- feature_cols = bundle.get("feature_cols", None) # ok if None (pure pipeline)
17
  except Exception as e:
18
- # Fail fast with a clear message in the Space logs
19
  raise RuntimeError(f"Failed to load model bundle '{BUNDLE_FILENAME}': {e}")
20
 
21
- # ── 3) OPTIONAL: feature-engineering used during training ──────────────────────
22
- # If you engineered these in the notebook, keep them here. If not, they are harmless.
23
  def add_features(df: pd.DataFrame) -> pd.DataFrame:
24
  df = df.copy()
25
- # Product code prefix from Product_Id (if present)
26
  if "Product_Id" in df.columns:
27
  df["Product_Category_Code"] = df["Product_Id"].astype(str).str[:2]
28
-
29
- # Store age from establishment year (if present)
30
  if "Store_Establishment_Year" in df.columns:
31
- # keep same constant year you used in training; adjust if needed
32
  df["Store_Age"] = 2025 - pd.to_numeric(df["Store_Establishment_Year"], errors="coerce")
33
-
34
- # Price per weight (if both present)
35
  if ("Product_MRP" in df.columns) and ("Product_Weight" in df.columns):
36
  w = pd.to_numeric(df["Product_Weight"], errors="coerce").replace(0, np.nan)
37
  p = pd.to_numeric(df["Product_MRP"], errors="coerce")
38
  df["Price_per_weight"] = p / w
39
-
40
  return df
41
 
42
- # ── 4) FLASK APP ───────────────────────────────────────────────────────────────
43
  app = Flask(__name__)
44
 
45
  @app.route("/", methods=["GET"])
@@ -52,7 +38,6 @@ def health():
52
 
53
  @app.route("/schema", methods=["GET"])
54
  def schema():
55
- """Quick way to see which raw columns the backend expects before preprocessing."""
56
  return jsonify({
57
  "expects_columns_like": [
58
  "Product_Id", "Product_Weight", "Product_Sugar_Content",
@@ -61,22 +46,13 @@ def schema():
61
  "Store_Location_City_Type", "Store_Type"
62
  ],
63
  "engineers": ["Product_Category_Code", "Store_Age", "Price_per_weight"],
64
- "model_feature_cols": feature_cols # can be None if your model is a full pipeline
65
  }), 200
66
 
67
  @app.route("/predict", methods=["POST"])
68
  def predict():
69
- """
70
- Accepts:
71
- - a single JSON object, or
72
- - a list of JSON objects.
73
- Returns:
74
- {"predictions": [float, ...]}
75
- """
76
  try:
77
  payload = request.get_json(force=True)
78
-
79
- # Accept dict or list[dict]
80
  if isinstance(payload, dict):
81
  df = pd.DataFrame([payload])
82
  elif isinstance(payload, list):
@@ -84,31 +60,22 @@ def predict():
84
  else:
85
  return jsonify({"error": "Input must be a JSON object or a list of objects."}), 400
86
 
87
- # 1) Apply the same feature engineering used in training
88
  df = add_features(df)
89
 
90
- # 2) If you saved a feature list, align to it. Let the model/pipeline handle imputation/encoding.
91
  if feature_cols is not None:
92
- # Keep only the columns the model was trained on; add any missing as NaN
93
  for c in feature_cols:
94
  if c not in df.columns:
95
  df[c] = np.nan
96
  X = df[feature_cols]
97
  else:
98
- # No explicit feature list in bundle; pass raw (the pipeline inside model should handle it)
99
  X = df
100
 
101
- # 3) Predict
102
  preds = model.predict(X)
103
  preds = [float(p) for p in np.ravel(preds)]
104
-
105
  return jsonify({"predictions": preds}), 200
106
 
107
  except Exception as e:
108
- # Include traceback for fast debugging from the Space logs
109
  return jsonify({"error": str(e), "traceback": traceback.format_exc()}), 400
110
 
111
-
112
  if __name__ == "__main__":
113
- # For local docker run; in Spaces we use gunicorn (see your Dockerfile)
114
  app.run(host="0.0.0.0", port=5000)
 
4
  import numpy as np
5
  import traceback
6
 
7
+ BUNDLE_FILENAME = "best_model_random_forest.joblib" # must match the file in the repo
 
 
8
 
9
+ # Load bundle: {"model": fitted_pipeline_or_model, "feature_cols": [...]}
 
10
  try:
11
  bundle = joblib.load(BUNDLE_FILENAME)
12
  model = bundle["model"]
13
+ feature_cols = bundle.get("feature_cols", None)
14
  except Exception as e:
 
15
  raise RuntimeError(f"Failed to load model bundle '{BUNDLE_FILENAME}': {e}")
16
 
 
 
17
  def add_features(df: pd.DataFrame) -> pd.DataFrame:
18
  df = df.copy()
 
19
  if "Product_Id" in df.columns:
20
  df["Product_Category_Code"] = df["Product_Id"].astype(str).str[:2]
 
 
21
  if "Store_Establishment_Year" in df.columns:
 
22
  df["Store_Age"] = 2025 - pd.to_numeric(df["Store_Establishment_Year"], errors="coerce")
 
 
23
  if ("Product_MRP" in df.columns) and ("Product_Weight" in df.columns):
24
  w = pd.to_numeric(df["Product_Weight"], errors="coerce").replace(0, np.nan)
25
  p = pd.to_numeric(df["Product_MRP"], errors="coerce")
26
  df["Price_per_weight"] = p / w
 
27
  return df
28
 
 
29
  app = Flask(__name__)
30
 
31
  @app.route("/", methods=["GET"])
 
38
 
39
  @app.route("/schema", methods=["GET"])
40
  def schema():
 
41
  return jsonify({
42
  "expects_columns_like": [
43
  "Product_Id", "Product_Weight", "Product_Sugar_Content",
 
46
  "Store_Location_City_Type", "Store_Type"
47
  ],
48
  "engineers": ["Product_Category_Code", "Store_Age", "Price_per_weight"],
49
+ "model_feature_cols": feature_cols
50
  }), 200
51
 
52
  @app.route("/predict", methods=["POST"])
53
  def predict():
 
 
 
 
 
 
 
54
  try:
55
  payload = request.get_json(force=True)
 
 
56
  if isinstance(payload, dict):
57
  df = pd.DataFrame([payload])
58
  elif isinstance(payload, list):
 
60
  else:
61
  return jsonify({"error": "Input must be a JSON object or a list of objects."}), 400
62
 
 
63
  df = add_features(df)
64
 
 
65
  if feature_cols is not None:
 
66
  for c in feature_cols:
67
  if c not in df.columns:
68
  df[c] = np.nan
69
  X = df[feature_cols]
70
  else:
 
71
  X = df
72
 
 
73
  preds = model.predict(X)
74
  preds = [float(p) for p in np.ravel(preds)]
 
75
  return jsonify({"predictions": preds}), 200
76
 
77
  except Exception as e:
 
78
  return jsonify({"error": str(e), "traceback": traceback.format_exc()}), 400
79
 
 
80
  if __name__ == "__main__":
 
81
  app.run(host="0.0.0.0", port=5000)