Varun6299 commited on
Commit
4cd5505
·
verified ·
1 Parent(s): ccc1009

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +34 -68
  2. final_xgboost_pipeline.joblib +3 -0
app.py CHANGED
@@ -8,88 +8,54 @@ import traceback
8
  import numpy as np
9
  import os
10
 
11
- # --- Configuration ---
12
- MODEL_PATH = "final_xgboost_pipeline.pkl"
13
 
14
- # --- Initialize Flask App ---
15
- app = Flask("SuperKart Sales Predictor")
16
 
17
- # Load the model
18
- try:
19
- model = joblib.load(MODEL_PATH)
20
- print("Model loaded successfully.") # Add logging
21
- except Exception as e:
22
- print(f"Error loading model: {e}") # Log error
23
 
24
  # Define a route for the home page
25
- @app.get('/')
26
  def home():
27
  print("Home route accessed.") # Add logging
28
  return "Welcome to the SuperKart Store Product Sales Prediction API."
29
 
30
 
31
- @app.route("/predict", methods=['POST']) # The simple, unversioned route
32
  def predict_sales():
33
  """
34
  Receives product and store features, makes a sales prediction, and returns the result.
35
  """
36
 
37
- if model is None:
38
- return jsonify({'error': 'Prediction service unavailable. Model failed to load.'}), 503
39
-
40
- try:
41
- # 1. REMOVE force=True to enforce correct MIME type header
42
- data = request.get_json()
43
- print(f"Received prediction request with data: {data}")
44
-
45
- if not data:
46
- return jsonify({'error': 'Invalid or empty JSON data provided. Ensure Content-Type is application/json.'}), 400
47
-
48
- # --- Data Transformation ---
49
- try:
50
- # Create a one-row DataFrame
51
- input_df = pd.DataFrame([data])
52
-
53
- # 2. REMOVE MANUAL TYPE CONVERSION
54
- # A well-built ML pipeline should handle all feature transformations internally.
55
- # input_df['Store_Establishment_Year'] = input_df['Store_Establishment_Year'].astype(str)
56
-
57
- # output variable removed as it was only used for the previous error
58
-
59
- except KeyError as ke:
60
- return jsonify({'error': f'Missing required feature: {ke}. Please check all features are present.'}), 400
61
-
62
- except Exception as e:
63
- return jsonify({'error': 'Error processing input data format', 'details': str(e)}), 400
64
-
65
-
66
- # --- Prediction ---
67
- prediction = model.predict(input_df)[0]
68
-
69
- # Convert NumPy type to standard Python float for JSON serialization
70
- if isinstance(prediction, (np.float32, np.float64)):
71
- predicted_sales = float(prediction)
72
- else:
73
- predicted_sales = prediction # Should ideally be a float
74
-
75
- print(f"Prediction result: {predicted_sales:.2f}")
76
-
77
- # --- Response ---
78
- # 3. FIX: Return the actual predicted value instead of the string message
79
- return jsonify({
80
- 'status': 'success',
81
- 'predicted_sales': predicted_sales # Renamed key to 'predicted_sales' for clarity
82
- })
83
-
84
- except Exception as e:
85
- # Catch any unexpected runtime errors
86
- print(f"An unexpected internal error occurred: {e}")
87
- print(traceback.format_exc())
88
- return jsonify({
89
- 'error': 'Internal Server Error during prediction',
90
- 'details': str(e)
91
- }), 500
92
-
93
 
94
  # --- Local Runner (Optional: Comment out for production WSGI) ---
95
  if __name__ == '__main__':
 
8
  import numpy as np
9
  import os
10
 
 
 
11
 
12
+ # Initialize the Flask application
13
+ superKart_sales_predictor_api = Flask("SuperKart Sales Predictor")
14
 
15
+ # Load the trained machine learning model
16
+ model = joblib.load("final_xgboost_pipeline.joblib")
 
 
 
 
17
 
18
  # Define a route for the home page
19
+ @superKart_sales_predictor_api.get('/')
20
  def home():
21
  print("Home route accessed.") # Add logging
22
  return "Welcome to the SuperKart Store Product Sales Prediction API."
23
 
24
 
25
+ @superKart_sales_predictor_api.post("/predict") # The simple, unversioned route
26
  def predict_sales():
27
  """
28
  Receives product and store features, makes a sales prediction, and returns the result.
29
  """
30
 
31
+ # Get the JSON data from the request body
32
+ input_data = request.get_json()
33
+
34
+ sample = {
35
+ 'product_weight': input_data['Product_Weight'],
36
+ 'product_sugar_content': input_data['Product_Sugar_Content'],
37
+ 'product_allocated_area': input_data['Product_Allocated_Area'],
38
+ 'product_type': input_data['Product_Type'],
39
+ 'product_quantity': input_data[ 'Product_Quantity'],
40
+ 'product_mrp': input_data['Product_Quantity'],
41
+ 'store_establishment_year': input_data['Store_Establishment_Year'],
42
+ 'store_size': input_data['Store_Size'],
43
+ 'store_location_city_type': input_data['Store_Location_City_Type'],
44
+ 'store_type': input_data['Store_Type']
45
+ }
46
+
47
+ # Convert the extracted data into a Pandas DataFrame
48
+ input_data = pd.DataFrame([sample])
49
+
50
+ # Make prediction (get log_price)
51
+ predicted_sales = model.predict(input_data)[0]
52
+
53
+ # Convert predicted_price to Python float
54
+ predicted_sales = round(float(predicted_sales), 2)
55
+
56
+ # Return the actual price
57
+ return jsonify({'Predicted Sales (in dollars)': predicted_sales})
58
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  # --- Local Runner (Optional: Comment out for production WSGI) ---
61
  if __name__ == '__main__':
final_xgboost_pipeline.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d668d13238361ffedd8a48008caebc7f6ee763f4ad8b2d1c81925e7b26c4c0fd
3
+ size 4439513