Lokiiparihar commited on
Commit
1cf3f01
·
verified ·
1 Parent(s): 867a77e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -90
app.py CHANGED
@@ -1,99 +1,119 @@
1
- # Import necessary libraries
2
- import numpy as np
3
- import joblib # For loading the serialized model
4
- import pandas as pd # For data manipulation
5
- from flask import Flask, request, jsonify # For creating the Flask API
6
 
7
- print("--- app.py: Starting Flask application setup ---")
 
 
8
 
9
- # Initialize the Flask application
10
- superkart_sales_api = Flask("SuperKart Sales Predictor")
11
- print("--- app.py: Flask app initialized ---")
12
 
13
- # Load the trained machine learning model
 
 
 
14
  try:
15
  model = joblib.load("superkart_sales_model.pkl")
16
- print("--- app.py: Model loaded successfully ---")
17
  except Exception as e:
18
- print(f"--- app.py: ERROR loading model: {e} ---")
19
- raise # Re-raise to ensure the error is visible
20
-
21
- # Define a route for the home page (GET request)
22
- @superkart_sales_api.get('/')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def home():
24
- print("--- API: Home route accessed ---")
25
- """
26
- This function handles GET requests to the root URL ('/') of the API.
27
- It returns a simple welcome message.
28
- """
29
- return "Welcome to the SuperKart Sales Prediction API!"
30
-
31
- # Define an endpoint for single sales prediction (POST request)
32
- @superkart_sales_api.post('/v1/sales')
33
  def predict_sales():
34
- print("--- API: Single sales prediction route accessed ---")
35
- """
36
- This function handles POST requests to the '/v1/sales' endpoint.
37
- It expects a JSON payload containing product and store details and returns
38
- the predicted sales as a JSON response.
39
- """
40
- # Get the JSON data from the request body
41
- input_data_json = request.get_json()
42
-
43
- # Extract relevant features from the JSON data, matching x_train columns
44
- # The model expects original feature names before one-hot encoding
45
- sample = {
46
- 'Product_Id': input_data_json['Product_Id'],
47
- 'Product_Weight': input_data_json['Product_Weight'],
48
- 'Product_Sugar_Content': input_data_json['Product_Sugar_Content'],
49
- 'Product_Allocated_Area': input_data_json['Product_Allocated_Area'],
50
- 'Product_Type': input_data_json['Product_Type'],
51
- 'Product_MRP': input_data_json['Product_MRP'],
52
- 'Store_Id': input_data_json['Store_Id'],
53
- 'Store_Size': input_data_json['Store_Size'],
54
- 'Store_Location_City_Type': input_data_json['Store_Location_City_Type'],
55
- 'Store_Current_Age': input_data_json['Store_Current_Age']
56
- }
57
-
58
- # Convert the extracted data into a Pandas DataFrame
59
- input_df = pd.DataFrame([sample])
60
-
61
- # Make prediction
62
- predicted_sales = model.predict(input_df)[0]
63
-
64
- # Convert predicted_sales to Python float and round
65
- predicted_sales = round(float(predicted_sales), 2)
66
-
67
- # Return the predicted sales
68
- return jsonify({'Predicted Sales': predicted_sales})
69
-
70
-
71
- # Define an endpoint for batch prediction (POST request)
72
- @superkart_sales_api.post('/v1/salesbatch')
73
  def predict_sales_batch():
74
- print("--- API: Batch sales prediction route accessed ---")
75
- """
76
- This function handles POST requests to the '/v1/salesbatch' endpoint.
77
- It expects a CSV file containing product and store details for multiple entries
78
- and returns the predicted sales as a list in the JSON response.
79
- """
80
- # Get the uploaded CSV file from the request
81
- file = request.files['file']
82
-
83
- # Read the CSV file into a Pandas DataFrame
84
- input_df_batch = pd.read_csv(file)
85
-
86
- # Make predictions for all entries in the DataFrame
87
- predicted_sales_batch = model.predict(input_df_batch).tolist()
88
-
89
- # Round each prediction and convert to float
90
- predicted_sales_batch = [round(float(s), 2) for s in predicted_sales_batch]
91
-
92
- # Return the predictions list as a JSON response
93
- return jsonify({'Predicted Sales': predicted_sales_batch})
94
-
95
- # Run the Flask application in debug mode if this script is executed directly
96
- # When deploying with Gunicorn, this block is usually commented out or removed
97
- if __name__ == '__main__':
98
- print("--- app.py: Running Flask app in debug mode ---")
99
- superkart_sales_api.run(debug=True)
 
 
 
 
 
 
 
1
+ # ===============================
2
+ # SuperKart Sales Prediction API
3
+ # ===============================
 
 
4
 
5
+ import joblib
6
+ import pandas as pd
7
+ from flask import Flask, request, jsonify
8
 
9
+ print("Starting SuperKart Sales Prediction API...")
 
 
10
 
11
+ # Initialize Flask app
12
+ app = Flask(__name__)
13
+
14
+ # Load trained model
15
  try:
16
  model = joblib.load("superkart_sales_model.pkl")
17
+ print("Model loaded successfully")
18
  except Exception as e:
19
+ print("ERROR loading model:", e)
20
+ raise
21
+
22
+ # Required columns expected by the trained pipeline
23
+ REQUIRED_COLUMNS = [
24
+ "Product_Weight",
25
+ "Product_Allocated_Area",
26
+ "Product_MRP",
27
+ "Store_Current_Age",
28
+ "Product_Sugar_Content",
29
+ "Store_Id",
30
+ "Store_Size",
31
+ "Store_Location_City_Type",
32
+ "Store_Type",
33
+ "Product_Id",
34
+ "Product_Type"
35
+ ]
36
+
37
+ # -------------------------------
38
+ # Health Check / Home Route
39
+ # -------------------------------
40
+ @app.get("/")
41
  def home():
42
+ return jsonify({
43
+ "message": "SuperKart Sales Prediction API is running",
44
+ "status": "OK"
45
+ })
46
+
47
+ # -------------------------------
48
+ # Single Prediction Endpoint
49
+ # -------------------------------
50
+ @app.post("/v1/sales")
51
  def predict_sales():
52
+ try:
53
+ input_data = request.get_json()
54
+
55
+ if not input_data:
56
+ return jsonify({"error": "Invalid or empty JSON payload"}), 400
57
+
58
+ # Convert to DataFrame
59
+ df = pd.DataFrame([input_data])
60
+
61
+ # Ensure all required columns exist
62
+ for col in REQUIRED_COLUMNS:
63
+ if col not in df.columns:
64
+ df[col] = None # handled by imputers
65
+
66
+ # Reorder columns to match training
67
+ df = df[REQUIRED_COLUMNS]
68
+
69
+ # Make prediction
70
+ prediction = model.predict(df)[0]
71
+
72
+ return jsonify({
73
+ "Predicted Sales": round(float(prediction), 2)
74
+ })
75
+
76
+ except Exception as e:
77
+ print("Prediction error:", str(e))
78
+ return jsonify({
79
+ "error": "Prediction failed",
80
+ "details": str(e)
81
+ }), 500
82
+
83
+ # -------------------------------
84
+ # Batch Prediction Endpoint
85
+ # -------------------------------
86
+ @app.post("/v1/salesbatch")
 
 
 
 
87
  def predict_sales_batch():
88
+ try:
89
+ if "file" not in request.files:
90
+ return jsonify({"error": "CSV file not provided"}), 400
91
+
92
+ file = request.files["file"]
93
+ df = pd.read_csv(file)
94
+
95
+ # Ensure required columns
96
+ for col in REQUIRED_COLUMNS:
97
+ if col not in df.columns:
98
+ df[col] = None
99
+
100
+ df = df[REQUIRED_COLUMNS]
101
+
102
+ predictions = model.predict(df)
103
+
104
+ return jsonify({
105
+ "Predicted Sales": [round(float(p), 2) for p in predictions]
106
+ })
107
+
108
+ except Exception as e:
109
+ print("Batch prediction error:", str(e))
110
+ return jsonify({
111
+ "error": "Batch prediction failed",
112
+ "details": str(e)
113
+ }), 500
114
+
115
+ # -------------------------------
116
+ # Local Run (Not used on HF)
117
+ # -------------------------------
118
+ if __name__ == "__main__":
119
+ app.run(dedug=True)