mdsalmon159 commited on
Commit
cd620ca
·
verified ·
1 Parent(s): 28f80a4

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. Dockerfile +6 -1
  2. app.py +10 -46
  3. requirements.txt +9 -9
Dockerfile CHANGED
@@ -7,7 +7,12 @@ WORKDIR /app
7
  COPY . .
8
 
9
  # Install dependencies from the requirements file without using cache to reduce image size
10
- RUN pip install --no-cache-dir --upgrade -r requirements.txt
 
 
 
 
 
11
 
12
  # Define the command to start the application using Gunicorn with 4 worker processes
13
  # - '-w 4': Uses 4 worker processes for handling requests
 
7
  COPY . .
8
 
9
  # Install dependencies from the requirements file without using cache to reduce image size
10
+ RUN pip install --upgrade pip
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ # expose port (Spaces listens on 7860)
14
+ ENV PORT=7860
15
+ EXPOSE 7860
16
 
17
  # Define the command to start the application using Gunicorn with 4 worker processes
18
  # - '-w 4': Uses 4 worker processes for handling requests
app.py CHANGED
@@ -1,4 +1,5 @@
1
 
 
2
  import numpy as np
3
  import pandas as pd
4
  import joblib
@@ -7,28 +8,21 @@ from flask import Flask, request, jsonify
7
  # initiate flask application
8
  sales_price_prediction_api = Flask("SuperKart Sales Price Prediction API")
9
 
10
- # Load the trained model
11
  model = joblib.load("superkart_prediction.joblib")
12
 
13
 
14
- # -------------------- HOME ROUTE --------------------
15
  @sales_price_prediction_api.get("/")
16
  def home():
17
  return "Welcome to the SuperKart Sales Prediction API!"
18
 
19
 
20
- # -------------------- SINGLE SALES PREDICTION --------------------
21
  @sales_price_prediction_api.post("/v1/sales")
22
  def predict_sales_single():
23
- """
24
- Handles POST requests to predict sales for a single product.
25
- Expects JSON input with required features.
26
- """
27
-
28
  try:
29
- sales_data = request.get_json()
30
-
31
- # Extract features
32
  sample = {
33
  'Product_Id': sales_data.get('Product_Id'),
34
  'Product_Weight': sales_data.get('Product_Weight'),
@@ -42,66 +36,36 @@ def predict_sales_single():
42
  'Store_Location_City_Type': sales_data.get('Store_Location_City_Type'),
43
  'Store_Type': sales_data.get('Store_Type')
44
  }
45
-
46
- # Convert into DataFrame
47
  input_df = pd.DataFrame([sample])
48
-
49
- # Predict log-sales
50
  log_pred = model.predict(input_df)[0]
51
-
52
- # Convert log prediction to actual sales
53
  predicted_sale = round(float(np.exp(log_pred)), 2)
54
-
55
- return jsonify({"predicted_sales_in_dollars": predicted_sale})
56
-
57
  except Exception as e:
58
  return jsonify({"error": str(e)}), 400
59
 
60
 
61
- # -------------------- BATCH SALES PREDICTION --------------------
62
  @sales_price_prediction_api.post("/v1/sales/batch")
63
  def predict_sales_batch():
64
- """
65
- Handles batch prediction using uploaded CSV.
66
- Returns a dict of ID → predicted_sales.
67
- """
68
-
69
  try:
70
- # Get uploaded CSV file
71
  file = request.files.get("file")
72
  if file is None:
73
  return jsonify({"error": "No CSV file uploaded under key 'file'"}), 400
74
-
75
  df = pd.read_csv(file)
76
-
77
- # Predict log-sales
78
  log_preds = model.predict(df).tolist()
79
-
80
- # Convert log values to sales
81
  predictions = [round(float(np.exp(p)), 2) for p in log_preds]
82
-
83
- # Determine ID column
84
- id_col = None
85
- for col in ["id", "ID", "Product_Id"]:
86
- if col in df.columns:
87
- id_col = col
88
- break
89
-
90
  if id_col:
91
  ids = df[id_col].astype(str).tolist()
92
  result = dict(zip(ids, predictions))
93
  else:
94
- # fallback to index-based prediction
95
  result = {str(i): predictions[i] for i in range(len(predictions))}
96
-
97
- return jsonify({"predictions": result})
98
-
99
  except Exception as e:
100
  return jsonify({"error": str(e)}), 400
101
 
102
 
103
- # -------------------- RUN APP LOCALLY --------------------
104
- # Hugging Face uses gunicorn to run "app", so we expose the variable below:
105
  app = sales_price_prediction_api
106
 
107
  if __name__ == "__main__":
 
1
 
2
+ # backend_files/app.py
3
  import numpy as np
4
  import pandas as pd
5
  import joblib
 
8
  # initiate flask application
9
  sales_price_prediction_api = Flask("SuperKart Sales Price Prediction API")
10
 
11
+ # Load the trained model (ensure file exists in repo root or adjust path)
12
  model = joblib.load("superkart_prediction.joblib")
13
 
14
 
15
+ # HOME ROUTE
16
  @sales_price_prediction_api.get("/")
17
  def home():
18
  return "Welcome to the SuperKart Sales Prediction API!"
19
 
20
 
21
+ # SINGLE SALES PREDICTION
22
  @sales_price_prediction_api.post("/v1/sales")
23
  def predict_sales_single():
 
 
 
 
 
24
  try:
25
+ sales_data = request.get_json(force=True)
 
 
26
  sample = {
27
  'Product_Id': sales_data.get('Product_Id'),
28
  'Product_Weight': sales_data.get('Product_Weight'),
 
36
  'Store_Location_City_Type': sales_data.get('Store_Location_City_Type'),
37
  'Store_Type': sales_data.get('Store_Type')
38
  }
 
 
39
  input_df = pd.DataFrame([sample])
 
 
40
  log_pred = model.predict(input_df)[0]
 
 
41
  predicted_sale = round(float(np.exp(log_pred)), 2)
42
+ return jsonify({"predicted_sales_in_dollars": predicted_sale}), 200
 
 
43
  except Exception as e:
44
  return jsonify({"error": str(e)}), 400
45
 
46
 
47
+ # BATCH SALES PREDICTION
48
  @sales_price_prediction_api.post("/v1/sales/batch")
49
  def predict_sales_batch():
 
 
 
 
 
50
  try:
 
51
  file = request.files.get("file")
52
  if file is None:
53
  return jsonify({"error": "No CSV file uploaded under key 'file'"}), 400
 
54
  df = pd.read_csv(file)
 
 
55
  log_preds = model.predict(df).tolist()
 
 
56
  predictions = [round(float(np.exp(p)), 2) for p in log_preds]
57
+ id_col = next((c for c in ("id", "ID", "Product_Id") if c in df.columns), None)
 
 
 
 
 
 
 
58
  if id_col:
59
  ids = df[id_col].astype(str).tolist()
60
  result = dict(zip(ids, predictions))
61
  else:
 
62
  result = {str(i): predictions[i] for i in range(len(predictions))}
63
+ return jsonify({"predictions": result}), 200
 
 
64
  except Exception as e:
65
  return jsonify({"error": str(e)}), 400
66
 
67
 
68
+ # expose WSGI callable expected by Gunicorn
 
69
  app = sales_price_prediction_api
70
 
71
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -1,13 +1,13 @@
1
- pandas == 2.2.2
2
- numpy == 2.0.2
 
 
 
 
 
 
 
3
  scikit-learn == 1.6.1
4
- xgboost == 2.1.4
5
- joblib == 1.4.2
6
  Werkzeug == 2.2.2
7
- flask == 2.2.2
8
- gunicorn == 20.1.0
9
- requests == 2.28.1
10
  uvicorn[standard]
11
  streamlit == 1.43.2
12
- flask-cors
13
- Flask
 
1
+ Flask==2.2.2
2
+ flask-cors==3.0.10
3
+ joblib==1.4.2
4
+ numpy==2.0.2
5
+ pandas==2.2.2
6
+ scikit-learn==1.6.1
7
+ xgboost==2.1.4
8
+ gunicorn==20.1.0
9
+ requests==2.28.1
10
  scikit-learn == 1.6.1
 
 
11
  Werkzeug == 2.2.2
 
 
 
12
  uvicorn[standard]
13
  streamlit == 1.43.2