TheHumanAgent commited on
Commit
cf7a16c
Β·
verified Β·
1 Parent(s): 7cd2d96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -134
app.py CHANGED
@@ -1,134 +1,110 @@
1
- import joblib
2
- import pandas as pd
3
- from flask import Flask, request, jsonify
4
- import numpy as np
5
-
6
- # Initialize Flask app
7
- sales_forecast_api = Flask("SuperKart Sales Forecast API")
8
-
9
- # Load the trained sales forecasting model
10
- model = joblib.load("superkart_sales_forecast_model.pkl")
11
-
12
- # Define a route for the home page
13
- @sales_forecast_api.get('/')
14
- def home():
15
- return "Welcome to the SuperKart Sales Forecasting API! πŸ›’πŸ“Š"
16
-
17
- # Define an endpoint to predict sales for a single product-store combination
18
- @sales_forecast_api.post('/v1/predict_sales')
19
- def predict_sales():
20
- try:
21
- # Get JSON data from the request
22
- input_data = request.get_json()
23
-
24
- # Extract relevant features from the input data
25
- sample = {
26
- 'Product_Weight': input_data['Product_Weight'],
27
- 'Product_Sugar_Content': input_data['Product_Sugar_Content'],
28
- 'Product_Allocated_Area': input_data['Product_Allocated_Area'],
29
- 'Product_Type': input_data['Product_Type'],
30
- 'Product_MRP': input_data['Product_MRP'],
31
- 'Store_Establishment_Year': input_data['Store_Establishment_Year'],
32
- 'Store_Size': input_data['Store_Size'],
33
- 'Store_Location_City_Type': input_data['Store_Location_City_Type'],
34
- 'Store_Type': input_data['Store_Type']
35
- }
36
-
37
- # Convert the extracted data into a DataFrame
38
- input_df = pd.DataFrame([sample])
39
-
40
- # Make sales prediction using the trained model
41
- prediction = model.predict(input_df)[0]
42
-
43
- # Return the prediction as a JSON response
44
- return jsonify({
45
- 'Product_Id': input_data.get('Product_Id', 'N/A'),
46
- 'Store_Id': input_data.get('Store_Id', 'N/A'),
47
- 'Predicted_Sales': round(prediction, 2),
48
- 'Currency': 'INR',
49
- 'Status': 'Success'
50
- })
51
-
52
- except Exception as e:
53
- return jsonify({
54
- 'Error': str(e),
55
- 'Status': 'Failed'
56
- }), 400
57
-
58
- # Define an endpoint to predict sales for a batch of product-store combinations
59
- @sales_forecast_api.post('/v1/predict_sales_batch')
60
- def predict_sales_batch():
61
- try:
62
- # Get the uploaded CSV file from the request
63
- file = request.files['file']
64
-
65
- # Read the file into a DataFrame
66
- input_data = pd.read_csv(file)
67
-
68
- # Select only the required features for prediction
69
- feature_columns = [
70
- 'Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area',
71
- 'Product_Type', 'Product_MRP', 'Store_Establishment_Year',
72
- 'Store_Size', 'Store_Location_City_Type', 'Store_Type'
73
- ]
74
-
75
- # Prepare data for prediction
76
- prediction_data = input_data[feature_columns]
77
-
78
- # Make predictions for the batch data
79
- predictions = model.predict(prediction_data)
80
-
81
- # Create output with Product_Id and Store_Id mapping
82
- output_list = []
83
- for i, (_, row) in enumerate(input_data.iterrows()):
84
- prediction_entry = {
85
- 'Product_Id': row.get('Product_Id', f'Product_{i}'),
86
- 'Store_Id': row.get('Store_Id', f'Store_{i}'),
87
- 'Predicted_Sales': round(predictions[i], 2)
88
- }
89
- output_list.append(prediction_entry)
90
-
91
- return jsonify({
92
- 'Predictions': output_list,
93
- 'Total_Records': len(predictions),
94
- 'Currency': 'INR',
95
- 'Status': 'Success'
96
- })
97
-
98
- except Exception as e:
99
- return jsonify({
100
- 'Error': str(e),
101
- 'Status': 'Failed'
102
- }), 400
103
-
104
- # Health check endpoint
105
- @sales_forecast_api.get('/health')
106
- def health_check():
107
- return jsonify({
108
- 'Status': 'API is running',
109
- 'Model': 'XGBoost Sales Forecasting Model',
110
- 'Version': '1.0',
111
- 'Deployment': 'Hugging Face Spaces'
112
- })
113
-
114
- # Get model information
115
- @sales_forecast_api.get('/model_info')
116
- def model_info():
117
- return jsonify({
118
- 'Model_Name': 'SuperKart Sales Forecasting Model',
119
- 'Model_Type': 'XGBoost Regressor',
120
- 'Features': [
121
- 'Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area',
122
- 'Product_Type', 'Product_MRP', 'Store_Establishment_Year',
123
- 'Store_Size', 'Store_Location_City_Type', 'Store_Type'
124
- ],
125
- 'Target': 'Product_Store_Sales_Total',
126
- 'Performance': {
127
- 'Test_RMSE': 286.57,
128
- 'Test_R_Squared': 0.928
129
- }
130
- })
131
-
132
- # Run the Flask app
133
- if __name__ == '__main__':
134
- sales_forecast_api.run(debug=True, host='0.0.0.0', port=7860) # Port 7860 for Hugging Face
 
1
+ import joblib
2
+ import pandas as pd
3
+ from flask import Flask, request, jsonify
4
+ import numpy as np
5
+
6
+ # Initialize Flask app
7
+ sales_forecast_api = Flask("SuperKart Sales Forecast API")
8
+
9
+ # Load the trained sales forecasting model
10
+ model = joblib.load("superkart_sales_forecast_model.pkl")
11
+
12
+ # Define a route for the home page
13
+ @sales_forecast_api.get('/')
14
+ def home():
15
+ return "Welcome to the SuperKart Sales Forecasting API! πŸ›’πŸ“Š"
16
+
17
+ # Define an endpoint to predict sales for a single product-store combination
18
+ @sales_forecast_api.post('/v1/predict_sales')
19
+ def predict_sales():
20
+ try:
21
+ # Get JSON data from the request
22
+ input_data = request.get_json()
23
+
24
+ # Extract relevant features from the input data
25
+ sample = {
26
+ 'Product_Weight': input_data['Product_Weight'],
27
+ 'Product_Sugar_Content': input_data['Product_Sugar_Content'],
28
+ 'Product_Allocated_Area': input_data['Product_Allocated_Area'],
29
+ 'Product_Type': input_data['Product_Type'],
30
+ 'Product_MRP': input_data['Product_MRP'],
31
+ 'Store_Establishment_Year': input_data['Store_Establishment_Year'],
32
+ 'Store_Size': input_data['Store_Size'],
33
+ 'Store_Location_City_Type': input_data['Store_Location_City_Type'],
34
+ 'Store_Type': input_data['Store_Type']
35
+ }
36
+
37
+ # Convert the extracted data into a DataFrame
38
+ input_df = pd.DataFrame([sample])
39
+
40
+ # Make sales prediction using the trained model
41
+ prediction = model.predict(input_df)[0]
42
+
43
+ # Convert NumPy float32 to Python float
44
+ prediction = float(prediction)
45
+
46
+ # Return the prediction as a JSON response
47
+ return jsonify({
48
+ 'Product_Id': input_data.get('Product_Id', 'N/A'),
49
+ 'Store_Id': input_data.get('Store_Id', 'N/A'),
50
+ 'Predicted_Sales': round(prediction, 2),
51
+ 'Currency': 'INR',
52
+ 'Status': 'Success'
53
+ })
54
+
55
+ except Exception as e:
56
+ return jsonify({
57
+ 'Error': str(e),
58
+ 'Status': 'Failed'
59
+ }), 400
60
+
61
+ # Define an endpoint to predict sales for a batch of product-store combinations
62
+ @sales_forecast_api.post('/v1/predict_sales_batch')
63
+ def predict_sales_batch():
64
+ try:
65
+ # Get the uploaded CSV file from the request
66
+ file = request.files['file']
67
+
68
+ # Read the file into a DataFrame
69
+ input_data = pd.read_csv(file)
70
+
71
+ # Select only the required features for prediction
72
+ feature_columns = [
73
+ 'Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area',
74
+ 'Product_Type', 'Product_MRP', 'Store_Establishment_Year',
75
+ 'Store_Size', 'Store_Location_City_Type', 'Store_Type'
76
+ ]
77
+
78
+ # Prepare data for prediction
79
+ prediction_data = input_data[feature_columns]
80
+
81
+ # Make predictions for the batch data
82
+ predictions = model.predict(prediction_data)
83
+
84
+ # Create output with Product_Id and Store_Id mapping
85
+ output_list = []
86
+ for i, (_, row) in enumerate(input_data.iterrows()):
87
+ prediction_entry = {
88
+ 'Product_Id': row.get('Product_Id', f'Product_{i}'),
89
+ 'Store_Id': row.get('Store_Id', f'Store_{i}'),
90
+ 'Predicted_Sales': float(predictions[i])
91
+ }
92
+ output_list.append(prediction_entry)
93
+
94
+ return jsonify({
95
+ 'Predictions': output_list,
96
+ 'Total_Records': len(predictions),
97
+ 'Currency': 'INR',
98
+ 'Status': 'Success'
99
+ })
100
+
101
+ except Exception as e:
102
+ return jsonify({
103
+ 'Error': str(e),
104
+ 'Status': 'Failed'
105
+ }), 400
106
+
107
+
108
+ # Run the Flask app
109
+ if __name__ == '__main__':
110
+ sales_forecast_api.run(debug=True, host='0.0.0.0', port=7860) # Port 7860 for Hugging Face