DD009 commited on
Commit
d01df06
·
verified ·
1 Parent(s): 90f5ae5

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +76 -66
app.py CHANGED
@@ -1,21 +1,13 @@
1
  import streamlit as st
2
  import pandas as pd
3
- import joblib
4
- import numpy as np
5
  from datetime import datetime
6
 
7
- # Load the trained model
8
- @st.cache_resource
9
- def load_model():
10
- return joblib.load("SuperKart_model_v1_0.joblib")
11
 
12
- model = load_model()
13
-
14
- # Streamlit UI for Sales Prediction
15
- st.title("Retail Product Sales Prediction App")
16
- st.write("This tool predicts the total sales for a product in a retail store based on product and store characteristics.")
17
-
18
- st.subheader("Enter the product and store details:")
19
 
20
  # Create two columns for better layout
21
  col1, col2 = st.columns(2)
@@ -46,67 +38,85 @@ with col2:
46
  "Departmental Store", "Food Mart"
47
  ])
48
 
49
- # Calculate derived features
50
- store_age = current_year - establishment_year
51
- product_density = product_weight / (product_area + 1e-6)
52
- price_per_weight = product_mrp / (product_weight + 1e-6)
53
-
54
- # Convert user input into a DataFrame
55
- input_data = pd.DataFrame([{
56
- 'Product_Weight': product_weight,
57
- 'Product_Sugar_Content': product_sugar,
58
- 'Product_Allocated_Area': product_area,
59
- 'Product_Type': product_type,
60
- 'Product_MRP': product_mrp,
61
- 'Store_Id': store_id,
62
- 'Store_Establishment_Year': establishment_year,
63
- 'Store_Size': store_size,
64
- 'Store_Location_City_Type': city_type,
65
- 'Store_Type': store_type,
66
- 'Store_Age': store_age,
67
- 'Product_Density': product_density,
68
- 'Price_Per_Unit_Weight': price_per_weight,
69
- 'Product_Size_Category': 'Small' if product_weight <= 10 else ('Medium' if product_weight <= 15 else 'Large'),
70
- 'Store_Tier_Size': f"{city_type}_{store_size}"
71
- }])
72
 
73
- # Predict button
74
  if st.button("Predict Sales"):
75
  try:
76
- prediction = model.predict(input_data)
77
- st.success(f"Predicted Sales Total: ${prediction[0]:.2f}")
78
-
79
- # Show some statistics
80
- st.subheader("Statistics")
81
- st.write(f"Store Age: {store_age} years")
82
- st.write(f"Product Density: {product_density:.2f} kg/sqm")
83
- st.write(f"Price per Unit Weight: ${price_per_weight:.2f}/kg")
84
-
 
 
 
85
  except Exception as e:
86
- st.error(f"Error in prediction: {str(e)}")
 
 
 
 
 
 
 
87
 
88
- # Add some helpful information
89
- st.sidebar.markdown("""
90
- **Data Statistics:**
91
- - Average Product Weight: 12.65 kg
92
- - Average Allocated Area: 0.07 sqm
93
- - Average MRP: $147.03
94
- - Average Sales: $3464.00
95
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- # Add a sample data button
 
98
  if st.sidebar.button("Load Sample Data"):
99
  sample_data = {
100
- 'Product_Weight': 12.66,
101
- 'Product_Sugar_Content': "Low Sugar",
102
- 'Product_Allocated_Area': 0.027,
103
- 'Product_Type': "Frozen Foods",
104
- 'Product_MRP': 117.08,
105
- 'Store_Id': "OUT004",
106
- 'Store_Establishment_Year': 2009,
107
- 'Store_Size': "Medium",
108
- 'Store_Location_City_Type': "Tier 2",
109
- 'Store_Type': "Supermarket Type2"
110
  }
111
 
112
  # Update all widgets with sample data
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import requests
 
4
  from datetime import datetime
5
 
6
+ # Set the title of the Streamlit app
7
+ st.title("Retail Product Sales Prediction")
 
 
8
 
9
+ # Section for single prediction
10
+ st.subheader("Single Product-Store Prediction")
 
 
 
 
 
11
 
12
  # Create two columns for better layout
13
  col1, col2 = st.columns(2)
 
38
  "Departmental Store", "Food Mart"
39
  ])
40
 
41
+ # Prepare input data
42
+ input_data = {
43
+ "product_weight": product_weight,
44
+ "product_sugar_content": product_sugar,
45
+ "product_allocated_area": product_area,
46
+ "product_type": product_type,
47
+ "product_mrp": product_mrp,
48
+ "store_id": store_id,
49
+ "store_establishment_year": establishment_year,
50
+ "store_size": store_size,
51
+ "store_location_city_type": city_type,
52
+ "store_type": store_type
53
+ }
 
 
 
 
 
 
 
 
 
 
54
 
55
+ # Make prediction when the "Predict" button is clicked
56
  if st.button("Predict Sales"):
57
  try:
58
+ response = requests.post("http://DD009-SuperKartBackend/v1/sales", json=input_data)
59
+ if response.status_code == 200:
60
+ result = response.json()
61
+ st.success(f"Predicted Sales Total: ${result['predicted_sales']}")
62
+
63
+ # Display additional metrics
64
+ st.markdown("**Additional Metrics**")
65
+ st.write(f"- Store Age: {result['store_age']} years")
66
+ st.write(f"- Product Density: {result['product_density']} kg/sqm")
67
+ st.write(f"- Price per Unit Weight: ${result['price_per_weight']}/kg")
68
+ else:
69
+ st.error(f"Error making prediction: {response.json().get('error', 'Unknown error')}")
70
  except Exception as e:
71
+ st.error(f"Connection error: {str(e)}")
72
+
73
+ # Section for batch prediction
74
+ st.subheader("Batch Prediction")
75
+ st.write("Upload a CSV file containing multiple product-store combinations")
76
+
77
+ # File uploader for batch predictions
78
+ uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
79
 
80
+ if uploaded_file is not None:
81
+ if st.button("Predict Batch Sales"):
82
+ try:
83
+ files = {'file': uploaded_file.getvalue()}
84
+ response = requests.post("http://DD009-SuperKartBackend/v1/salesbatch", files=files)
85
+
86
+ if response.status_code == 200:
87
+ results = response.json()['predictions']
88
+ results_df = pd.DataFrame(results)
89
+
90
+ st.success("Batch predictions completed!")
91
+ st.dataframe(results_df)
92
+
93
+ # Download button for results
94
+ csv = results_df.to_csv(index=False)
95
+ st.download_button(
96
+ label="Download predictions as CSV",
97
+ data=csv,
98
+ file_name='sales_predictions.csv',
99
+ mime='text/csv'
100
+ )
101
+ else:
102
+ st.error(f"Error making predictions: {response.json().get('error', 'Unknown error')}")
103
+ except Exception as e:
104
+ st.error(f"Connection error: {str(e)}")
105
 
106
+ # Add sample data section
107
+ st.sidebar.markdown("### Sample Data")
108
  if st.sidebar.button("Load Sample Data"):
109
  sample_data = {
110
+ "product_weight": 12.66,
111
+ "product_sugar_content": "Low Sugar",
112
+ "product_allocated_area": 0.027,
113
+ "product_type": "Frozen Foods",
114
+ "product_mrp": 117.08,
115
+ "store_id": "OUT004",
116
+ "store_establishment_year": 2009,
117
+ "store_size": "Medium",
118
+ "store_location_city_type": "Tier 2",
119
+ "store_type": "Supermarket Type2"
120
  }
121
 
122
  # Update all widgets with sample data