Hugo014 commited on
Commit
d2b2b38
·
verified ·
1 Parent(s): 760c760

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +26 -36
app.py CHANGED
@@ -7,34 +7,30 @@ from flask import Flask, request, jsonify
7
  super_kart_api = Flask("Super Kart Price Predictor")
8
 
9
  # Load the trained machine learning model
10
- model_path = "super_kart_model_v1_0.joblib" # Path after upload (root)
11
- try:
12
- model = joblib.load(model_path)
13
- print(f"Model loaded successfully from {model_path}")
14
- except FileNotFoundError:
15
- raise FileNotFoundError(f"Model file not found at {model_path}. Ensure it's uploaded to the repo root.")
 
 
 
 
 
 
 
16
 
17
  # Define a route for the home page (GET request)
18
  @super_kart_api.get('/')
19
  def home():
20
- """
21
- This function handles GET requests to the root URL ('/') of the API.
22
- It returns a simple welcome message.
23
- """
24
  return "Welcome to the Super Kart Price Prediction API!"
25
 
26
  # Define an endpoint for single product sales prediction (POST request)
27
  @super_kart_api.post('/v1/sales')
28
  def predict_sales():
29
- """
30
- This function handles POST requests to the '/v1/sales' endpoint.
31
- It expects a JSON payload containing product and store details and returns
32
- the predicted sales total as a JSON response.
33
- """
34
- # Get the JSON data from the request body
35
  input_data = request.get_json()
36
-
37
- # Extract relevant features from the JSON data
38
  sample = {
39
  'Product_Weight': input_data['Product_Weight'],
40
  'Product_Sugar_Content': input_data['Product_Sugar_Content'],
@@ -46,35 +42,29 @@ def predict_sales():
46
  'Store_Location_City_Type': input_data['Store_Location_City_Type'],
47
  'Store_Type': input_data['Store_Type']
48
  }
49
-
50
- # Convert the extracted data into a Pandas DataFrame
51
  features_df = pd.DataFrame([sample])
52
-
53
- # Apply one-hot encoding for nominal columns (matching training)
54
  features_df = pd.get_dummies(features_df, columns=['Product_Type', 'Store_Type'], drop_first=True)
55
-
56
- # Apply ordinal encoding (based on provided orders)
57
  sugar_mapping = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2}
58
  size_mapping = {'Small': 0, 'Medium': 1, 'High': 2}
59
  city_mapping = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2}
60
-
61
  features_df['Product_Sugar_Content'] = features_df['Product_Sugar_Content'].map(sugar_mapping)
62
  features_df['Store_Size'] = features_df['Store_Size'].map(size_mapping)
63
  features_df['Store_Location_City_Type'] = features_df['Store_Location_City_Type'].map(city_mapping)
64
-
65
- # Make prediction (assuming direct sales prediction; adjust if log-transformed)
 
 
 
66
  predicted_sales = model.predict(features_df)[0]
67
-
68
- # If your model predicts log(sales), uncomment and use this instead:
69
- # predicted_log_sales = model.predict(features_df)
70
- # predicted_sales = np.exp(predicted_log_sales)
71
-
72
- # Convert to Python float and round to 2 decimals
73
  predicted_sales = round(float(predicted_sales), 2)
74
-
75
- # Return the predicted sales total
76
  return jsonify({'Predicted Sales Total (in dollars)': predicted_sales})
77
 
78
- # Run the app (for testing locally; remove or adjust for production)
79
  if __name__ == '__main__':
80
  super_kart_api.run(debug=True)
 
7
  super_kart_api = Flask("Super Kart Price Predictor")
8
 
9
  # Load the trained machine learning model
10
+ model = joblib.load("backend_files/super_kart_model_v1_0.joblib")
11
+
12
+ # Expected feature names from training (copy these from your training code or model inspection)
13
+ EXPECTED_COLUMNS = [
14
+ 'Product_Type_Baking Goods', 'Product_Type_Breads', 'Product_Type_Breakfast', 'Product_Type_Canned',
15
+ 'Product_Type_Dairy', 'Product_Type_Frozen Foods', 'Product_Type_Fruits and Vegetables',
16
+ 'Product_Type_Hard Drinks', 'Product_Type_Health and Hygiene', 'Product_Type_Household',
17
+ 'Product_Type_Meat', 'Product_Type_Others', 'Product_Type_Seafood', 'Product_Type_Snack Foods',
18
+ 'Product_Type_Soft Drinks', 'Product_Type_Starchy Foods', 'Store_Type_Departmental Store',
19
+ 'Store_Type_Food Mart', 'Store_Type_Supermarket Type1', 'Store_Type_Supermarket Type2',
20
+ 'Product_Sugar_Content', 'Store_Size', 'Store_Location_City_Type', 'Product_Weight',
21
+ 'Product_Allocated_Area', 'Product_MRP', 'Store_Establishment_Year'
22
+ ]
23
 
24
  # Define a route for the home page (GET request)
25
  @super_kart_api.get('/')
26
  def home():
 
 
 
 
27
  return "Welcome to the Super Kart Price Prediction API!"
28
 
29
  # Define an endpoint for single product sales prediction (POST request)
30
  @super_kart_api.post('/v1/sales')
31
  def predict_sales():
 
 
 
 
 
 
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'],
 
42
  'Store_Location_City_Type': input_data['Store_Location_City_Type'],
43
  'Store_Type': input_data['Store_Type']
44
  }
45
+
 
46
  features_df = pd.DataFrame([sample])
47
+
48
+ # Apply one-hot encoding
49
  features_df = pd.get_dummies(features_df, columns=['Product_Type', 'Store_Type'], drop_first=True)
50
+
51
+ # Apply ordinal encoding
52
  sugar_mapping = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2}
53
  size_mapping = {'Small': 0, 'Medium': 1, 'High': 2}
54
  city_mapping = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2}
55
+
56
  features_df['Product_Sugar_Content'] = features_df['Product_Sugar_Content'].map(sugar_mapping)
57
  features_df['Store_Size'] = features_df['Store_Size'].map(size_mapping)
58
  features_df['Store_Location_City_Type'] = features_df['Store_Location_City_Type'].map(city_mapping)
59
+
60
+ # Align columns with expected model features (add missing with 0, drop extras)
61
+ features_df = features_df.reindex(columns=EXPECTED_COLUMNS, fill_value=0)
62
+
63
+ # Make prediction
64
  predicted_sales = model.predict(features_df)[0]
 
 
 
 
 
 
65
  predicted_sales = round(float(predicted_sales), 2)
66
+
 
67
  return jsonify({'Predicted Sales Total (in dollars)': predicted_sales})
68
 
 
69
  if __name__ == '__main__':
70
  super_kart_api.run(debug=True)