HacksterT commited on
Commit
8a836d9
·
verified ·
1 Parent(s): d1dbd35

Update backend code

Browse files
Files changed (5) hide show
  1. .dockerignore +0 -16
  2. Dockerfile +2 -32
  3. README.md +16 -167
  4. app.py +7 -121
  5. requirements.txt +1 -5
.dockerignore CHANGED
@@ -1,19 +1,3 @@
1
- # SuperKart API - Docker ignore file
2
  __pycache__/
3
  *.pyc
4
- *.pyo
5
- *.pyd
6
- .Python
7
- *.so
8
- .pytest_cache/
9
- .coverage
10
- .env
11
- .venv/
12
- venv/
13
- *.log
14
  .git/
15
- .gitignore
16
- README.md
17
- *.md
18
- .DS_Store
19
- Thumbs.db
 
 
1
  __pycache__/
2
  *.pyc
 
 
 
 
 
 
 
 
 
 
3
  .git/
 
 
 
 
 
Dockerfile CHANGED
@@ -1,43 +1,13 @@
1
- # SuperKart Sales Forecasting API - Dockerfile
2
  FROM python:3.12-slim
3
 
4
- # Set working directory
5
  WORKDIR /app
6
 
7
- # Set environment variables
8
- ENV PYTHONDONTWRITEBYTECODE=1
9
- ENV PYTHONUNBUFFERED=1
10
- ENV FLASK_APP=app.py
11
- ENV FLASK_ENV=production
12
-
13
- # Install system dependencies
14
- RUN apt-get update && apt-get install -y \
15
- gcc \
16
- g++ \
17
- && rm -rf /var/lib/apt/lists/*
18
-
19
- # Copy requirements first for better caching
20
  COPY requirements.txt .
 
21
 
22
- # Install Python dependencies
23
- RUN pip install --no-cache-dir --upgrade pip
24
- RUN pip install --no-cache-dir -r requirements.txt
25
-
26
- # Copy application files
27
  COPY app.py .
28
  COPY models/ ./models/
29
 
30
- # Create non-root user for security
31
- RUN useradd --create-home --shell /bin/bash app
32
- RUN chown -R app:app /app
33
- USER app
34
-
35
- # Expose port
36
  EXPOSE 7860
37
 
38
- # Health check
39
- HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
40
- CMD curl -f http://localhost:7860/ || exit 1
41
-
42
- # Run the application
43
- CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "2", "--timeout", "120", "app:app"]
 
 
1
  FROM python:3.12-slim
2
 
 
3
  WORKDIR /app
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  COPY requirements.txt .
6
+ RUN pip install -r requirements.txt
7
 
 
 
 
 
 
8
  COPY app.py .
9
  COPY models/ ./models/
10
 
 
 
 
 
 
 
11
  EXPOSE 7860
12
 
13
+ CMD ["python", "app.py"]
 
 
 
 
 
README.md CHANGED
@@ -1,167 +1,16 @@
1
- ---
2
- title: SuperKart Sales Forecasting API
3
- emoji: 🛒
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: docker
7
- pinned: false
8
- license: mit
9
- short_description: ML API for SuperKart sales forecasting with XGBoost
10
- ---
11
-
12
- A production-ready machine learning API for predicting SuperKart product sales using XGBoost regression model.
13
-
14
- ## Model Performance
15
-
16
- - **R² Score**: 92.11% (excellent variance explanation)
17
- - **RMSE**: $299.50 (low prediction error)
18
- - **MAPE**: 4.06% (high accuracy)
19
- - **Overfitting Gap**: 4.11% (good generalization)
20
-
21
- ## API Endpoints
22
-
23
- ### Health Check
24
-
25
- ```http
26
- GET /
27
- ```
28
-
29
- Returns API status and model information.
30
-
31
- ### Single Prediction
32
-
33
- ```http
34
- POST /predict
35
- Content-Type: application/json
36
-
37
- {
38
- "Product_Weight": 12.5,
39
- "Product_Sugar_Content": "Low Sugar",
40
- "Product_Type": "Dairy",
41
- "Product_MRP": 150.0,
42
- "Store_Id": "OUT003",
43
- "Store_Establishment_Year": 2009,
44
- "Store_Size": "Medium",
45
- "Store_Location_City_Type": "Tier 1",
46
- "Store_Type": "Departmental Store"
47
- }
48
- ```
49
-
50
- ### Batch Predictions
51
-
52
- ```http
53
- POST /predict-batch
54
- Content-Type: application/json
55
-
56
- [
57
- {
58
- "Product_Weight": 12.5,
59
- "Product_Sugar_Content": "Low Sugar",
60
- ...
61
- },
62
- {
63
- "Product_Weight": 8.0,
64
- "Product_Sugar_Content": "Regular",
65
- ...
66
- }
67
- ]
68
- ```
69
-
70
- ### Model Information
71
-
72
- ```http
73
- GET /model-info
74
- ```
75
-
76
- Returns model metadata and performance metrics.
77
-
78
- ## Model Features
79
-
80
- The model uses the following input features:
81
-
82
- - **Product_Weight** (numerical) - Weight of the product
83
- - **Product_Sugar_Content** (categorical) - Sugar content level
84
- - **Product_Type** (categorical) - Type of product
85
- - **Product_MRP** (numerical) - Maximum retail price
86
- - **Store_Id** (categorical) - Store identifier
87
- - **Store_Establishment_Year** (numerical) - Year store was established
88
- - **Store_Size** (categorical) - Size of the store
89
- - **Store_Location_City_Type** (categorical) - City tier location
90
- - **Store_Type** (categorical) - Type of store
91
-
92
- ## Technology Stack
93
-
94
- - **Framework**: Flask 2.3.3
95
- - **Model**: XGBoost Regressor (Tuned)
96
- - **Preprocessing**: scikit-learn 1.6.1
97
- - **Deployment**: Docker + Gunicorn
98
- - **Serialization**: joblib 1.4.2
99
-
100
- ## Usage Example
101
-
102
- ```python
103
- import requests
104
-
105
- # API endpoint
106
- url = "https://hackstert-greatlearningproject.hf.space/predict"
107
-
108
- # Sample data
109
- data = {
110
- "Product_Weight": 12.5,
111
- "Product_Sugar_Content": "Low Sugar",
112
- "Product_Type": "Dairy",
113
- "Product_MRP": 150.0,
114
- "Store_Id": "OUT003",
115
- "Store_Establishment_Year": 2009,
116
- "Store_Size": "Medium",
117
- "Store_Location_City_Type": "Tier 1",
118
- "Store_Type": "Departmental Store"
119
- }
120
-
121
- # Make prediction
122
- response = requests.post(url, json=data)
123
- result = response.json()
124
- print(f"Predicted Sales: {result['prediction_formatted']}")
125
- ```
126
-
127
- ## Model Training
128
-
129
- This model was trained on the SuperKart dataset with:
130
-
131
- - **8,763 training samples** with comprehensive preprocessing
132
- - **Hyperparameter tuning** via GridSearchCV
133
- - **Cross-validation** for robust evaluation
134
- - **Feature engineering** including data quality fixes
135
- - **Stratified train-test split** preserving sales distribution
136
-
137
- ### Key Features by Importance
138
-
139
- 1. Product_MRP (47.9%) - Most important predictor
140
- 2. Product_Weight (10.7%) - Second most important
141
- 3. Store characteristics - Location, size, type
142
- 4. Product attributes - Type, sugar content
143
-
144
- ## Development
145
-
146
- ### Data Science Pipeline
147
-
148
- - Data quality assessment and cleaning
149
- - Exploratory data analysis and visualization
150
- - Feature engineering and preprocessing
151
- - Model selection and hyperparameter tuning
152
- - Performance evaluation and validation
153
-
154
- ### Deployment Pipeline
155
-
156
- - Model serialization with joblib
157
- - Flask API development with error handling
158
- - Docker containerization for production
159
- - Hugging Face Spaces deployment
160
-
161
- ## License
162
-
163
- MIT License - Feel free to use for educational and commercial purposes.
164
-
165
- ---
166
-
167
- **Developed as part of Great Learning Course 7 - Machine Learning Deployment**
 
1
+ ---
2
+ title: SuperKart Sales Forecasting API
3
+ emoji: 🛒
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ ---
9
+
10
+ # SuperKart Sales Forecasting API
11
+
12
+ Machine learning API for sales forecasting using XGBoost.
13
+
14
+ ## Endpoints
15
+ - GET / - Health check
16
+ - POST /predict - Sales prediction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -5,150 +5,36 @@ import joblib
5
  import pandas as pd
6
  import numpy as np
7
  from datetime import datetime
8
- import os
9
 
10
- # Initialize Flask app
11
  app = Flask(__name__)
12
-
13
- # Enable CORS for all routes and origins
14
  CORS(app)
15
 
16
- # Global variable for model
17
- model = None
18
-
19
- def load_model():
20
- """Load the serialized model"""
21
- global model
22
-
23
- try:
24
- # Load the complete model (simplified approach)
25
- model = joblib.load('models/superkart_pipeline_20250804_140625.pkl')
26
-
27
- print("Model loaded successfully")
28
- return True
29
-
30
- except Exception as e:
31
- print(f"Error loading model: {str(e)}")
32
- return False
33
 
34
  @app.route('/', methods=['GET'])
35
  def home():
36
- """Health check endpoint"""
37
  return jsonify({
38
  'status': 'healthy',
39
  'message': 'SuperKart Sales Forecasting API',
40
- 'model_loaded': model is not None,
41
- 'timestamp': datetime.now().isoformat()
42
  })
43
 
44
  @app.route('/predict', methods=['POST'])
45
  def predict_sales():
46
- """Main prediction endpoint"""
47
  try:
48
- # Check if model is loaded
49
- if model is None:
50
- return jsonify({
51
- 'error': 'Model not loaded',
52
- 'status': 'failed'
53
- }), 500
54
-
55
- # Get JSON data from request
56
  data = request.get_json()
57
-
58
- if not data:
59
- return jsonify({
60
- 'error': 'No data provided',
61
- 'status': 'failed'
62
- }), 400
63
-
64
- # Convert to DataFrame
65
  input_df = pd.DataFrame([data])
66
-
67
- # Make prediction using the model (simplified)
68
  prediction = model.predict(input_df)
69
 
70
- # Return prediction
71
  return jsonify({
72
  'prediction': float(prediction[0]),
73
  'prediction_formatted': f"${prediction[0]:.2f}",
74
- 'status': 'success',
75
- 'timestamp': datetime.now().isoformat()
76
- })
77
-
78
- except Exception as e:
79
- return jsonify({
80
- 'error': str(e),
81
- 'status': 'failed',
82
- 'timestamp': datetime.now().isoformat()
83
- }), 500
84
-
85
- @app.route('/model-info', methods=['GET'])
86
- def model_info():
87
- """Get model information"""
88
- if model is None:
89
- return jsonify({
90
- 'error': 'Model not available',
91
- 'status': 'failed'
92
- }), 500
93
-
94
- return jsonify({
95
- 'model_type': str(type(model)),
96
- 'model_loaded': True,
97
- 'status': 'success'
98
- })
99
-
100
- @app.route('/predict-batch', methods=['POST'])
101
- def predict_batch():
102
- """Batch prediction endpoint for multiple records"""
103
- try:
104
- if model is None:
105
- return jsonify({
106
- 'error': 'Model not loaded',
107
- 'status': 'failed'
108
- }), 500
109
-
110
- # Get JSON data (expecting list of records)
111
- data = request.get_json()
112
-
113
- if not data or not isinstance(data, list):
114
- return jsonify({
115
- 'error': 'Data must be a list of records',
116
- 'status': 'failed'
117
- }), 400
118
-
119
- # Convert to DataFrame
120
- input_df = pd.DataFrame(data)
121
-
122
- # Make predictions (simplified)
123
- predictions = model.predict(input_df)
124
-
125
- # Format results
126
- results = []
127
- for i, pred in enumerate(predictions):
128
- results.append({
129
- 'record_id': i,
130
- 'prediction': float(pred),
131
- 'prediction_formatted': f"${pred:.2f}"
132
- })
133
-
134
- return jsonify({
135
- 'predictions': results,
136
- 'total_records': len(results),
137
- 'status': 'success',
138
- 'timestamp': datetime.now().isoformat()
139
  })
140
-
141
  except Exception as e:
142
- return jsonify({
143
- 'error': str(e),
144
- 'status': 'failed',
145
- 'timestamp': datetime.now().isoformat()
146
- }), 500
147
 
148
  if __name__ == '__main__':
149
- # Load model on startup
150
- if load_model():
151
- print("Starting SuperKart Sales Forecasting API...")
152
- app.run(host='0.0.0.0', port=5000, debug=True)
153
- else:
154
- print("Failed to start API - Model loading failed")
 
5
  import pandas as pd
6
  import numpy as np
7
  from datetime import datetime
 
8
 
 
9
  app = Flask(__name__)
 
 
10
  CORS(app)
11
 
12
+ # Load model on startup
13
+ deployment_package = joblib.load('models/superkart_deployment_package_{timestamp}.pkl')
14
+ model = deployment_package['model']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  @app.route('/', methods=['GET'])
17
  def home():
 
18
  return jsonify({
19
  'status': 'healthy',
20
  'message': 'SuperKart Sales Forecasting API',
21
+ 'model_loaded': True
 
22
  })
23
 
24
  @app.route('/predict', methods=['POST'])
25
  def predict_sales():
 
26
  try:
 
 
 
 
 
 
 
 
27
  data = request.get_json()
 
 
 
 
 
 
 
 
28
  input_df = pd.DataFrame([data])
 
 
29
  prediction = model.predict(input_df)
30
 
 
31
  return jsonify({
32
  'prediction': float(prediction[0]),
33
  'prediction_formatted': f"${prediction[0]:.2f}",
34
+ 'status': 'success'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  })
 
36
  except Exception as e:
37
+ return jsonify({'error': str(e), 'status': 'failed'}), 500
 
 
 
 
38
 
39
  if __name__ == '__main__':
40
+ app.run(host='0.0.0.0', port=5000, debug=True)
 
 
 
 
 
requirements.txt CHANGED
@@ -1,12 +1,11 @@
1
  # SuperKart Sales Forecasting API - Dependencies
2
- # Updated: 2025-08-09 - Force rebuild for model loading fix
3
  # Core web framework
4
  Flask==2.3.3
5
  Werkzeug==2.3.7
6
 
7
  # Data processing and machine learning
8
  pandas==2.2.3
9
- numpy==2.0.2
10
  scikit-learn==1.6.1
11
  xgboost==2.1.4
12
 
@@ -16,9 +15,6 @@ joblib==1.4.2
16
  # HTTP and JSON handling
17
  requests==2.31.0
18
 
19
- # CORS support for cross-origin requests
20
- Flask-CORS==4.0.0
21
-
22
  # Production WSGI server
23
  gunicorn==21.2.0
24
 
 
1
  # SuperKart Sales Forecasting API - Dependencies
 
2
  # Core web framework
3
  Flask==2.3.3
4
  Werkzeug==2.3.7
5
 
6
  # Data processing and machine learning
7
  pandas==2.2.3
8
+ numpy>=1.19.3,<2.0
9
  scikit-learn==1.6.1
10
  xgboost==2.1.4
11
 
 
15
  # HTTP and JSON handling
16
  requests==2.31.0
17
 
 
 
 
18
  # Production WSGI server
19
  gunicorn==21.2.0
20