HacksterT commited on
Commit
ffadcda
·
verified ·
1 Parent(s): 382765e

Upload folder using huggingface_hub

Browse files
.dockerignore ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Exclude project status file (contains sensitive token)
2
+ project_status.md
3
+
4
+ # Python cache files
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+ *.so
9
+
10
+ # Environment files
11
+ .env
12
+ .venv
13
+ env/
14
+ venv/
15
+
16
+ # IDE files
17
+ .vscode/
18
+ .idea/
19
+ *.swp
20
+ *.swo
21
+
22
+ # OS files
23
+ .DS_Store
24
+ Thumbs.db
25
+
26
+ # Logs
27
+ *.log
28
+
29
+ # Temporary files
30
+ *.tmp
31
+ *.temp
32
+
33
+ # Upload script with sensitive token
34
+ upload script.py
35
+
36
+ # Model files that are too large (if any)
37
+ # *.pkl
38
+
39
+ # Jupyter notebook checkpoints
40
+ .ipynb_checkpoints/
Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"]
README.md CHANGED
@@ -1,12 +1,167 @@
1
- ---
2
- title: GreatLearningProject
3
- emoji: 📉
4
- colorFrom: pink
5
- colorTo: gray
6
- sdk: docker
7
- pinned: false
8
- license: mit
9
- short_description: This is the final project of an exciting course.
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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**
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from flask import Flask, request, jsonify
3
+ import joblib
4
+ import pandas as pd
5
+ import numpy as np
6
+ from datetime import datetime
7
+ import os
8
+
9
+ # Initialize Flask app
10
+ app = Flask(__name__)
11
+
12
+ # Global variables for model components
13
+ model_pipeline = None
14
+ model_metadata = None
15
+
16
+ def load_model_components():
17
+ """Load the serialized model components"""
18
+ global model_pipeline, model_metadata
19
+
20
+ try:
21
+ # Load the complete pipeline
22
+ model_pipeline = joblib.load('models/superkart_pipeline_20250804_140625.pkl')
23
+
24
+ # Load model metadata
25
+ model_metadata = joblib.load('models/superkart_metadata_20250804_140625.pkl')
26
+
27
+ print("Model components 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_version': model_metadata['version'] if model_metadata else 'unknown',
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_pipeline 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 pipeline
68
+ prediction = model_pipeline.predict_sales(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
+ 'model_version': model_metadata['version']
77
+ })
78
+
79
+ except Exception as e:
80
+ return jsonify({
81
+ 'error': str(e),
82
+ 'status': 'failed',
83
+ 'timestamp': datetime.now().isoformat()
84
+ }), 500
85
+
86
+ @app.route('/model-info', methods=['GET'])
87
+ def model_info():
88
+ """Get model information and performance metrics"""
89
+ if model_metadata is None:
90
+ return jsonify({
91
+ 'error': 'Model metadata not available',
92
+ 'status': 'failed'
93
+ }), 500
94
+
95
+ return jsonify({
96
+ 'model_name': model_metadata['model_name'],
97
+ 'algorithm': model_metadata['algorithm'],
98
+ 'version': model_metadata['version'],
99
+ 'performance_metrics': model_metadata['performance_metrics'],
100
+ 'created_date': model_metadata['created_date'],
101
+ 'status': 'success'
102
+ })
103
+
104
+ @app.route('/predict-batch', methods=['POST'])
105
+ def predict_batch():
106
+ """Batch prediction endpoint for multiple records"""
107
+ try:
108
+ if model_pipeline is None:
109
+ return jsonify({
110
+ 'error': 'Model not loaded',
111
+ 'status': 'failed'
112
+ }), 500
113
+
114
+ # Get JSON data (expecting list of records)
115
+ data = request.get_json()
116
+
117
+ if not data or not isinstance(data, list):
118
+ return jsonify({
119
+ 'error': 'Data must be a list of records',
120
+ 'status': 'failed'
121
+ }), 400
122
+
123
+ # Convert to DataFrame
124
+ input_df = pd.DataFrame(data)
125
+
126
+ # Make predictions
127
+ predictions = model_pipeline.predict_sales(input_df)
128
+
129
+ # Format results
130
+ results = []
131
+ for i, pred in enumerate(predictions):
132
+ results.append({
133
+ 'record_id': i,
134
+ 'prediction': float(pred),
135
+ 'prediction_formatted': f"${pred:.2f}"
136
+ })
137
+
138
+ return jsonify({
139
+ 'predictions': results,
140
+ 'total_records': len(results),
141
+ 'status': 'success',
142
+ 'timestamp': datetime.now().isoformat(),
143
+ 'model_version': model_metadata['version']
144
+ })
145
+
146
+ except Exception as e:
147
+ return jsonify({
148
+ 'error': str(e),
149
+ 'status': 'failed',
150
+ 'timestamp': datetime.now().isoformat()
151
+ }), 500
152
+
153
+ if __name__ == '__main__':
154
+ # Load model components on startup
155
+ if load_model_components():
156
+ print("Starting SuperKart Sales Forecasting API...")
157
+ app.run(host='0.0.0.0', port=5000, debug=True)
158
+ else:
159
+ print("Failed to start API - Model loading failed")
models/superkart_metadata_20250804_140625.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:255965cd6cebb15c4a50492c3cbaa33dfd0db12ccd43950d913493318d941732
3
+ size 503
models/superkart_pipeline_20250804_140625.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:824d564d2f76061e2598a39171108c0a1639b9b21e56fb2e2ffa666c9eeb2969
3
+ size 401877
requirements.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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==2.0.2
9
+ scikit-learn==1.6.1
10
+ xgboost==2.1.4
11
+
12
+ # Model serialization
13
+ joblib==1.4.2
14
+
15
+ # HTTP and JSON handling
16
+ requests==2.31.0
17
+
18
+ # Production WSGI server
19
+ gunicorn==21.2.0
20
+
21
+ # Environment and configuration
22
+ python-dotenv==1.0.0
23
+
24
+ # Logging and monitoring
25
+ flask-cors==4.0.0