Rizwan9 commited on
Commit
fa3ceed
ยท
verified ยท
1 Parent(s): dac3b63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -30
app.py CHANGED
@@ -1,39 +1,80 @@
1
-
2
- from flask import Flask, request, jsonify
3
- import joblib
4
  import pandas as pd
5
 
6
- app = Flask(__name__)
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Load the serialized model
9
- model = joblib.load('best_sales_forecasting_model.pkl')
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- @app.route('/')
12
- def home():
13
- return "Sales Forecasting Backend is running!"
14
 
15
- @app.route('/predict', methods=['POST'])
16
- def predict():
17
- try:
18
- data = request.get_json(force=True)
19
- # Convert the incoming data to a pandas DataFrame
20
- # Assuming the incoming data is a list of dictionaries, where each dictionary is a data point
21
- input_data = pd.DataFrame(data)
 
 
 
 
 
22
 
23
- # Ensure the columns are in the same order as the training data
24
- # This assumes you have access to the columns from your training data (X_train)
25
- # You might need to adjust this part based on how you handle feature ordering
26
- # For demonstration, let's assume the input data has the same columns in the same order
27
- # In a real application, you might need to reorder columns or handle missing ones
 
 
 
 
 
 
28
 
29
- # Make predictions
30
- predictions = model.predict(input_data)
31
 
32
- # Return predictions as a JSON response
33
- return jsonify(predictions.tolist())
34
- except Exception as e:
35
- return jsonify({'error': str(e)})
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- if __name__ == '__main__':
38
- # Running on 0.0.0.0 makes it accessible externally, useful for deployment
39
- app.run(host='0.0.0.0', port=5000)
 
1
+ import os
2
+ import requests
3
+ import streamlit as st
4
  import pandas as pd
5
 
6
+ st.set_page_config(page_title="SuperKart Sales Forecast", layout="centered")
7
+ st.title("๐Ÿ›’ SuperKart Sales Forecast")
8
+
9
+ # Read backend URL from secret or sidebar input
10
+ DEFAULT_BACKEND = os.getenv("BACKEND_URL", "").strip()
11
+ backend_url = st.sidebar.text_input(
12
+ "Backend /predict URL",
13
+ value=DEFAULT_BACKEND,
14
+ help="From BACKEND_URL secret; you can override here."
15
+ )
16
+ st.sidebar.caption("Example: https://rizwan9--backend.hf.space/predict")
17
 
18
+ # Health check button
19
+ if st.sidebar.button("๐Ÿ”— Check Backend Connection"):
20
+ if not backend_url:
21
+ st.sidebar.error("Please enter backend URL first.")
22
+ else:
23
+ try:
24
+ health_url = backend_url.replace("/predict", "/")
25
+ r = requests.get(health_url, timeout=10)
26
+ if r.status_code == 200:
27
+ st.sidebar.success("โœ… Backend is reachable!")
28
+ else:
29
+ st.sidebar.warning(f"โš ๏ธ Backend responded with {r.status_code}")
30
+ except Exception as e:
31
+ st.sidebar.error(f"โŒ Could not connect: {e}")
32
 
33
+ st.markdown("Enter product & store details, then click **Predict**.")
 
 
34
 
35
+ col1, col2 = st.columns(2)
36
+ with col1:
37
+ Product_Weight = st.number_input("Product_Weight", min_value=0.0, value=12.65)
38
+ Product_Allocated_Area = st.number_input("Product_Allocated_Area", min_value=0.0, value=0.07)
39
+ Product_MRP = st.number_input("Product_MRP", min_value=0.0, value=147.0)
40
+ Store_Establishment_Year = st.number_input("Store_Establishment_Year", min_value=1900, max_value=2100, value=2005)
41
+ with col2:
42
+ Product_Sugar_Content = st.selectbox("Product_Sugar_Content", ["Low Sugar", "Regular", "No Sugar"])
43
+ Product_Type = st.text_input("Product_Type", "Dairy")
44
+ Store_Size = st.selectbox("Store_Size", ["High", "Medium", "Low"])
45
+ Store_Location_City_Type = st.selectbox("Store_Location_City_Type", ["Tier 1", "Tier 2", "Tier 3"])
46
+ Store_Type = st.selectbox("Store_Type", ["Departmental Store", "Supermarket Type 1", "Supermarket Type 2", "Food Mart"])
47
 
48
+ payload = {
49
+ "Product_Weight": Product_Weight,
50
+ "Product_Sugar_Content": Product_Sugar_Content,
51
+ "Product_Allocated_Area": Product_Allocated_Area,
52
+ "Product_Type": Product_Type,
53
+ "Product_MRP": Product_MRP,
54
+ "Store_Establishment_Year": int(Store_Establishment_Year),
55
+ "Store_Size": Store_Size,
56
+ "Store_Location_City_Type": Store_Location_City_Type,
57
+ "Store_Type": Store_Type
58
+ }
59
 
60
+ st.markdown("#### Request Payload (Preview)")
61
+ st.code(pd.DataFrame([payload]).to_json(orient="records", indent=2))
62
 
63
+ if st.button("๐Ÿ”ฎ Predict"):
64
+ if not backend_url:
65
+ st.error("Please set backend URL in sidebar.")
66
+ else:
67
+ try:
68
+ resp = requests.post(backend_url, json=[payload], timeout=20)
69
+ if resp.ok:
70
+ data = resp.json()
71
+ preds = data.get("predictions") or data.get("prediction")
72
+ if isinstance(preds, list):
73
+ st.success(f"**Predicted Sales:** {preds[0]:,.2f}")
74
+ else:
75
+ st.success(f"**Prediction:** {preds}")
76
+ else:
77
+ st.error(f"Backend error {resp.status_code}: {resp.text}")
78
+ except Exception as e:
79
+ st.error(f"Request failed: {e}")
80