HacksterT commited on
Commit
7f13127
·
verified ·
1 Parent(s): b799338

Force upload app.py - 1754763926

Browse files
Files changed (1) hide show
  1. app.py +85 -37
app.py CHANGED
@@ -1,37 +1,85 @@
1
- import streamlit as st
2
- import requests
3
-
4
- st.title("SuperKart Sales Forecasting")
5
-
6
- # Input fields matching class template structure
7
- Product_Weight = st.number_input("Product Weight", min_value=0.0, value=12.66)
8
- Product_Sugar_Content = st.selectbox("Product Sugar Content", ["Low Sugar", "Regular", "No Sugar"])
9
- Product_Allocated_Area = st.number_input("Product Allocated Area", min_value=0.0, value=0.1)
10
- Product_MRP = st.number_input("Product MRP", min_value=0.0, value=150.0)
11
- Store_Size = st.selectbox("Store Size", ["Small", "Medium", "High"])
12
- Store_Location_City_Type = st.selectbox("Store Location City Type", ["Tier 1", "Tier 2", "Tier 3"])
13
- Store_Type = st.selectbox("Store Type", ["Supermarket Type1", "Supermarket Type2", "Supermarket Type3", "Grocery Store"])
14
- Product_Id_char = st.selectbox("Product Id Char", ["F", "D", "N"])
15
- Store_Age_Years = st.number_input("Store Age Years", min_value=0, value=16)
16
- Product_Type_Category = st.selectbox("Product Type Category", ["Dairy", "Soft Drinks", "Meat", "Fruits and Vegetables", "Household", "Baking Goods", "Snack Foods", "Frozen Foods", "Breakfast", "Health and Hygiene", "Hard Drinks", "Canned", "Breads", "Starchy Foods", "Others", "Seafood"])
17
-
18
- product_data = {
19
- "Product_Weight": Product_Weight,
20
- "Product_Sugar_Content": Product_Sugar_Content,
21
- "Product_MRP": Product_MRP,
22
- "Store_Size": Store_Size,
23
- "Store_Location_City_Type": Store_Location_City_Type,
24
- "Store_Type": Store_Type,
25
- "Store_Establishment_Year": 2025 - Store_Age_Years, # Convert back to establishment year
26
- "Product_Type": Product_Type_Category,
27
- "Store_Id": Product_Id_char # Map to Store_Id
28
- }
29
-
30
- if st.button("Predict", type='primary'):
31
- response = requests.post("https://hackstert-greatlearningproject.hf.space/predict", json=product_data)
32
- if response.status_code == 200:
33
- result = response.json()
34
- predicted_sales = result["prediction"]
35
- st.write(f"Predicted Product Store Sales Total: ${predicted_sales:.2f}")
36
- else:
37
- st.error(f"Error in API request: {response.text}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from flask_cors import CORS
3
+ import joblib
4
+ import pandas as pd
5
+ import numpy as np
6
+ from datetime import datetime
7
+
8
+ app = Flask(__name__)
9
+ CORS(app)
10
+
11
+ # Load model components using joblib (class requirement)
12
+ print("Loading model components...")
13
+ try:
14
+ deployment_package = joblib.load('models/superkart_minimal.pkl')
15
+ model = deployment_package['model']
16
+ scaler = deployment_package['scaler']
17
+ metadata = deployment_package['metadata']
18
+ print("Model loaded successfully with joblib!")
19
+ except Exception as e:
20
+ print(f"Error loading model: {e}")
21
+ model = None
22
+ scaler = None
23
+ metadata = None
24
+
25
+ @app.route('/', methods=['GET'])
26
+ def home():
27
+ return jsonify({
28
+ 'status': 'healthy',
29
+ 'message': 'SuperKart Sales Forecasting API',
30
+ 'model_loaded': True
31
+ })
32
+
33
+ @app.route('/predict', methods=['POST'])
34
+ def predict_sales():
35
+ try:
36
+ data = request.get_json()
37
+
38
+ # Calculate Store_Age from Store_Establishment_Year (as done in training)
39
+ current_year = 2025 # Use consistent year as in training
40
+ if 'Store_Establishment_Year' in data:
41
+ data['Store_Age'] = current_year - data['Store_Establishment_Year']
42
+ del data['Store_Establishment_Year'] # Remove original field
43
+
44
+ input_df = pd.DataFrame([data])
45
+
46
+ # Apply same preprocessing as training: one-hot encoding for categorical features
47
+ categorical_cols = ['Product_Sugar_Content', 'Product_Type', 'Store_Id', 'Store_Size',
48
+ 'Store_Location_City_Type', 'Store_Type']
49
+
50
+ # One-hot encode categorical features (drop_first=True to match training)
51
+ input_encoded = pd.get_dummies(input_df, columns=categorical_cols, drop_first=True)
52
+
53
+ # Ensure we have all the same columns as training (30 features)
54
+ # Define all expected columns from training
55
+ training_columns = [
56
+ 'Product_Weight', 'Product_MRP', 'Store_Age',
57
+ 'Product_Sugar_Content_No Sugar', 'Product_Sugar_Content_Regular',
58
+ 'Product_Type_Breads', 'Product_Type_Breakfast', 'Product_Type_Canned',
59
+ 'Product_Type_Dairy', 'Product_Type_Frozen Foods', 'Product_Type_Fruits and Vegetables',
60
+ 'Product_Type_Hard Drinks', 'Product_Type_Health and Hygiene', 'Product_Type_Household',
61
+ 'Product_Type_Meat', 'Product_Type_Others', 'Product_Type_Seafood',
62
+ 'Product_Type_Snack Foods', 'Product_Type_Soft Drinks', 'Product_Type_Starchy Foods',
63
+ 'Store_Id_OUT002', 'Store_Id_OUT003', 'Store_Id_OUT004',
64
+ 'Store_Size_Medium', 'Store_Size_Small',
65
+ 'Store_Location_City_Type_Tier 2', 'Store_Location_City_Type_Tier 3',
66
+ 'Store_Type_Food Mart', 'Store_Type_Supermarket Type1', 'Store_Type_Supermarket Type2'
67
+ ]
68
+
69
+ # Reindex to match training columns (missing columns filled with 0)
70
+ input_final = input_encoded.reindex(columns=training_columns, fill_value=0)
71
+
72
+ # Scale the input data (essential for correct predictions)
73
+ input_scaled = scaler.transform(input_final)
74
+ prediction = model.predict(input_scaled)
75
+
76
+ return jsonify({
77
+ 'prediction': float(prediction[0]),
78
+ 'prediction_formatted': f"${prediction[0]:.2f}",
79
+ 'status': 'success'
80
+ })
81
+ except Exception as e:
82
+ return jsonify({'error': str(e), 'status': 'failed'}), 500
83
+
84
+ if __name__ == '__main__':
85
+ app.run(host='0.0.0.0', port=7860, debug=False)