HacksterT commited on
Commit
90d1abe
·
verified ·
1 Parent(s): b02f435

Force upload app.py - 1754763896

Browse files
Files changed (1) hide show
  1. app.py +37 -67
app.py CHANGED
@@ -1,67 +1,37 @@
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
- # Ensure columns are in the same order as training
47
- expected_columns = ['Product_Weight', 'Product_MRP', 'Product_Sugar_Content',
48
- 'Product_Type', 'Store_Id', 'Store_Size',
49
- 'Store_Location_City_Type', 'Store_Type', 'Store_Age']
50
-
51
- # Reorder columns to match training data
52
- input_df = input_df.reindex(columns=expected_columns)
53
-
54
- # Scale the input data (essential for correct predictions)
55
- input_scaled = scaler.transform(input_df)
56
- prediction = model.predict(input_scaled)
57
-
58
- return jsonify({
59
- 'prediction': float(prediction[0]),
60
- 'prediction_formatted': f"${prediction[0]:.2f}",
61
- 'status': 'success'
62
- })
63
- except Exception as e:
64
- return jsonify({'error': str(e), 'status': 'failed'}), 500
65
-
66
- if __name__ == '__main__':
67
- app.run(host='0.0.0.0', port=7860, debug=False)
 
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}")