Sricharan451706 commited on
Commit
1a32cd2
·
verified ·
1 Parent(s): 4f68a90

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +121 -0
app.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from flask import Flask, request, jsonify
3
+ import joblib
4
+ import pandas as pd
5
+ from datetime import datetime
6
+
7
+ app = Flask(__name__)
8
+
9
+ print("Starting SuperKart API...")
10
+
11
+ # Load complete pipeline
12
+ try:
13
+ pipeline = joblib.load('superkart_complete_pipeline.joblib')
14
+ print("Complete pipeline loaded successfully")
15
+ except Exception as e:
16
+ print(f"Error loading pipeline: {e}")
17
+ pipeline = None
18
+
19
+ @app.route('/')
20
+ def home():
21
+ return jsonify({
22
+ "message": "SuperKart Sales Prediction API",
23
+ "status": "active",
24
+ "model_loaded": pipeline is not None,
25
+ "endpoints": {
26
+ "predict": "/predict",
27
+ "health": "/health"
28
+ }
29
+ })
30
+
31
+ @app.route('/health')
32
+ def health():
33
+ return jsonify({
34
+ "status": "healthy",
35
+ "model_loaded": pipeline is not None,
36
+ "timestamp": datetime.now().isoformat()
37
+ })
38
+
39
+ @app.route('/predict', methods=['POST'])
40
+ def predict():
41
+ try:
42
+ if pipeline is None:
43
+ return jsonify({
44
+ "error": "Pipeline not loaded",
45
+ "status": "error"
46
+ }), 500
47
+
48
+ data = request.get_json()
49
+ if not data:
50
+ return jsonify({
51
+ "error": "No input data provided",
52
+ "status": "error"
53
+ }), 400
54
+
55
+ # Dynamic feature engineering in backend
56
+ current_year = datetime.now().year
57
+
58
+ # Calculate Store_Age dynamically
59
+ if 'Store_Establishment_Year' in data:
60
+ data['Store_Age'] = current_year - data['Store_Establishment_Year']
61
+
62
+ # Extract Product_Category_Code from Product_Id
63
+ if 'Product_Id' in data:
64
+ data['Product_Category_Code'] = data['Product_Id'][:2]
65
+ # Remove Product_Id as it's not needed for model input
66
+ data.pop('Product_Id')
67
+
68
+ # Required fields for model input (including derived features)
69
+ required_fields = [
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
+ missing_fields = [field for field in required_fields if field not in data]
76
+ if missing_fields:
77
+ return jsonify({
78
+ "error": f"Missing required fields: {missing_fields}",
79
+ "status": "error"
80
+ }), 400
81
+
82
+ # Create DataFrame for prediction (using only base features for model)
83
+ model_features = [
84
+ 'Product_Weight', 'Product_Sugar_Content', 'Product_Allocated_Area',
85
+ 'Product_Type', 'Product_MRP', 'Store_Establishment_Year',
86
+ 'Store_Size', 'Store_Location_City_Type', 'Store_Type'
87
+ ]
88
+
89
+ input_dict = {k: data[k] for k in model_features if k in data}
90
+ input_df = pd.DataFrame([input_dict])
91
+
92
+ print(f"Input data: {input_dict}")
93
+
94
+ # Make prediction using complete pipeline
95
+ prediction = pipeline.predict(input_df)
96
+
97
+ print(f"Prediction: ${prediction[0]:.2f}")
98
+
99
+ return jsonify({
100
+ "prediction": float(prediction[0]),
101
+ "status": "success",
102
+ "derived_features": {
103
+ "store_age": data.get('Store_Age'),
104
+ "product_category_code": data.get('Product_Category_Code')
105
+ },
106
+ "input_summary": {
107
+ "product_type": data.get('Product_Type'),
108
+ "store_type": data.get('Store_Type'),
109
+ "mrp": data.get('Product_MRP')
110
+ }
111
+ })
112
+
113
+ except Exception as e:
114
+ print(f"Prediction error: {str(e)}")
115
+ return jsonify({
116
+ "error": str(e),
117
+ "status": "error"
118
+ }), 500
119
+
120
+ if __name__ == '__main__':
121
+ app.run(host='0.0.0.0', port=7860, debug=False)