Rizwan9 commited on
Commit
43ba4ed
·
verified ·
1 Parent(s): 32d7bc7

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +18 -28
app.py CHANGED
@@ -1,42 +1,32 @@
1
- import os
2
  from flask import Flask, request, jsonify
3
  import joblib
4
  import pandas as pd
5
- from glob import glob
6
 
7
  app = Flask(__name__)
8
 
9
- # ---- Resolve model path robustly ----
10
- # Prefer env var, else default to the standard name we recommended.
11
- MODEL_PATH = os.getenv("MODEL_PATH", "superkart_sales_forecast.joblib")
12
-
13
- def load_model_bundle(path: str):
14
- if not os.path.exists(path):
15
- # Try to auto-find a .joblib in current dir (helpful during debugging)
16
- candidates = glob("*.joblib")
17
- raise FileNotFoundError(
18
- f"Model file not found: {path}. "
19
- f"Files present: {candidates}. "
20
- f"Set MODEL_PATH env var to the correct file name."
21
- )
22
- bundle = joblib.load(path)
23
- # Support both our recommended bundle {'pipeline': pipe} and plain pipeline
24
- if isinstance(bundle, dict) and "pipeline" in bundle:
25
- return bundle["pipeline"]
26
- return bundle # assume it's already a fitted pipeline
27
-
28
- pipe = load_model_bundle(MODEL_PATH)
29
-
30
- @app.get("/health")
31
  def health():
32
- return jsonify({"status": "ok", "model_path": MODEL_PATH})
33
 
34
- @app.post("/predict")
35
  def predict():
36
  data = request.get_json(force=True)
37
  df = pd.DataFrame([data]) if isinstance(data, dict) else pd.DataFrame(data)
38
  preds = pipe.predict(df)
39
- return jsonify({"predictions": [float(x) for x in preds]})
40
 
41
  if __name__ == "__main__":
42
- app.run(host="0.0.0.0", port=5000)
 
1
+
2
  from flask import Flask, request, jsonify
3
  import joblib
4
  import pandas as pd
5
+ import os
6
 
7
  app = Flask(__name__)
8
 
9
+ MODEL_PATH = os.getenv("MODEL_PATH", "best_model_random_forest.joblib")
10
+
11
+ if not os.path.exists(MODEL_PATH):
12
+ raise FileNotFoundError(f"Model file not found: {MODEL_PATH}. Please ensure it's uploaded to the Space.")
13
+
14
+ model_bundle = joblib.load(MODEL_PATH)
15
+ if isinstance(model_bundle, dict) and "pipeline" in model_bundle:
16
+ pipe = model_bundle["pipeline"]
17
+ else:
18
+ pipe = model_bundle
19
+
20
+ @app.route("/health", methods=["GET"])
 
 
 
 
 
 
 
 
 
 
21
  def health():
22
+ return jsonify({"status": "ok", "model": MODEL_PATH})
23
 
24
+ @app.route("/predict", methods=["POST"])
25
  def predict():
26
  data = request.get_json(force=True)
27
  df = pd.DataFrame([data]) if isinstance(data, dict) else pd.DataFrame(data)
28
  preds = pipe.predict(df)
29
+ return jsonify({"predictions": [float(p) for p in preds]})
30
 
31
  if __name__ == "__main__":
32
+ app.run(host="0.0.0.0", port=5000)