Lokiiparihar commited on
Commit
ae32f03
·
verified ·
1 Parent(s): b3b5caf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -99
app.py CHANGED
@@ -1,119 +1,101 @@
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("APP")
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)
 
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_Type': input_data_json['Store_type'],
54
+ 'Store_Size': input_data_json['Store_Size'],
55
+ 'Store_Location_City_Type': input_data_json['Store_Location_City_Type'],
56
+ 'Store_Current_Age': input_data_json['Store_Current_Age']
57
+ }
58
+
59
+ # Convert the extracted data into a Pandas DataFrame
60
+ input_df = pd.DataFrame([sample])
61
+
62
+ # Make prediction
63
+ predicted_sales = model.predict(input_df)[0]
64
+
65
+ # Convert predicted_sales to Python float and round
66
+ predicted_sales = round(float(predicted_sales), 2)
67
+
68
+ # Return the predicted sales
69
+ return jsonify({'Predicted Sales': predicted_sales})
70
+
71
+
72
+ # Define an endpoint for batch prediction (POST request)
73
+ @superkart_sales_api.post('/v1/salesbatch')
74
  def predict_sales_batch():
75
+ print("--- API: Batch sales prediction route accessed ---")
76
+ """
77
+ This function handles POST requests to the '/v1/salesbatch' endpoint.
78
+ It expects a CSV file containing product and store details for multiple entries
79
+ and returns the predicted sales as a list in the JSON response.
80
+ """
81
+ # Get the uploaded CSV file from the request
82
+ file = request.files['file']
83
 
84
+ # Read the CSV file into a Pandas DataFrame
85
+ input_df_batch = pd.read_csv(file)
 
 
86
 
87
+ # Make predictions for all entries in the DataFrame
88
+ predicted_sales_batch = model.predict(input_df_batch).tolist()
89
 
90
+ # Round each prediction and convert to float
91
+ predicted_sales_batch = [round(float(s), 2) for s in predicted_sales_batch]
92
 
93
+ # Return the predictions list as a JSON response
94
+ return jsonify({'Predicted Sales': predicted_sales_batch})
 
95
 
 
 
 
 
 
 
96
 
97
  # -------------------------------
98
  # Local Run (Not used on HF)
99
  # -------------------------------
100
  if __name__ == "__main__":
101
+ app.superkart_sales_api(dedug=True)