arnavarpit's picture
Upload folder using huggingface_hub
3082d1e verified
# Enhanced Streamlit Web App for SuperKart Sales Forecasting
import streamlit as st
import requests
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
# Page configuration
st.set_page_config(
page_title="SuperKart Sales Forecasting",
page_icon="πŸ›’",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better styling
st.markdown("""
<style>
.main-header {
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
padding: 2rem;
border-radius: 10px;
margin-bottom: 2rem;
text-align: center;
color: white;
}
.metric-card {
background: #f8f9fa;
padding: 1rem;
border-radius: 8px;
border: 1px solid #e9ecef;
margin: 0.5rem 0;
}
.prediction-result {
background: #d4edda;
border: 1px solid #c3e6cb;
padding: 1.5rem;
border-radius: 10px;
margin: 1rem 0;
text-align: center;
}
.sidebar-content {
background: #f8f9fa;
padding: 1rem;
border-radius: 8px;
margin-bottom: 1rem;
}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown("""
<div class="main-header">
<h1>πŸ›’ SuperKart Sales Forecasting System</h1>
<p>AI-Powered Revenue Prediction for Retail Excellence</p>
</div>
""", unsafe_allow_html=True)
# Sidebar for inputs
st.sidebar.header("πŸ“Š Product & Store Configuration")
# Add logo to sidebar
st.sidebar.image("https://cdn-icons-png.flaticon.com/512/2331/2331970.png", width=250, caption="SuperKart Analytics")
# Instructions in sidebar
st.sidebar.markdown("""
### πŸ” How to Use:
1. **Configure** product attributes
2. **Select** store characteristics
3. **Click** Predict to get forecast
4. **Analyze** results and insights
*All predictions are in USD ($)*
""")
# Create tabs for better organization
tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Prediction", "πŸ“Š Analytics", "ℹ️ About"])
with tab1:
# Create two columns for inputs
col1, col2 = st.columns(2)
with col1:
st.subheader("🏷️ Product Attributes")
Product_Weight = st.number_input(
"Product Weight (oz)",
min_value=0.0,
max_value=50.0,
value=12.66,
step=0.1,
help="Weight of the product in ounces"
)
Product_Sugar_Content = st.selectbox(
"Sugar Content Level",
["Low Sugar", "Regular", "No Sugar"],
help="Sugar content classification of the product"
)
Product_Allocated_Area = st.number_input(
"Allocated Shelf Area (sq. in.)",
min_value=0.0,
max_value=500.0,
value=100.0,
step=1.0,
help="Shelf space allocated to the product"
)
Product_MRP = st.number_input(
"Maximum Retail Price (USD)",
min_value=0.0,
max_value=1000.0,
value=150.0,
step=0.5,
help="Maximum retail price of the product"
)
Product_Type_Category = st.selectbox(
"Product Category",
["Perishables", "Non Perishables"],
help="Whether the product is perishable or not"
)
with col2:
st.subheader("πŸͺ Store Characteristics")
Store_Size = st.selectbox(
"Store Size Category",
["Small", "Medium", "High"],
help="Size classification of the store"
)
Store_Location_City_Type = st.selectbox(
"City Classification",
["Tier 1", "Tier 2", "Tier 3"],
help="Urban development tier of store location"
)
Store_Type = st.selectbox(
"Store Format",
["Supermarket Type1", "Supermarket Type2", "Departmental Store", "Food Mart"],
help="Type and format of the retail store"
)
Store_Age_Years = st.slider(
"Store Age (years)",
min_value=0,
max_value=30,
value=10,
help="Number of years the store has been operational"
)
# Display current configuration
st.subheader("πŸ”§ Current Configuration")
config_col1, config_col2, config_col3 = st.columns(3)
with config_col1:
st.metric("Product Weight", f"{Product_Weight} oz")
st.metric("Allocated Area", f"{Product_Allocated_Area} sq.in")
with config_col2:
st.metric("MRP", f"${Product_MRP}")
st.metric("Store Age", f"{Store_Age_Years} years")
with config_col3:
st.metric("Sugar Content", Product_Sugar_Content)
st.metric("Store Type", Store_Type)
# Apply log1p transform (must match backend model training)
Product_Allocated_Area_Log = np.log1p(Product_Allocated_Area)
# Prepare JSON payload for the backend
product_data = {
"Product_Weight": str(Product_Weight),
"Product_Sugar_Content": Product_Sugar_Content,
"Product_Allocated_Area": str(Product_Allocated_Area),
"Product_MRP": str(Product_MRP),
"Store_Size": Store_Size,
"Store_Location_City_Type": Store_Location_City_Type,
"Store_Type": Store_Type,
"Store_Age_Years": str(Store_Age_Years),
"Product_Type_Category": Product_Type_Category
}
# Prediction section
st.subheader("🎯 Sales Prediction")
predict_col1, predict_col2, predict_col3 = st.columns([1, 2, 1])
with predict_col2:
if st.button("πŸš€ Generate Prediction", type='primary', use_container_width=True):
with st.spinner('πŸ”„ Analyzing data and generating prediction...'):
try:
response = requests.post(
"https://arnavarpit-super-kart-backend.hf.space/v1/predict",
json=product_data,
timeout=30
)
if response.status_code == 200:
result = response.json()
predicted_sales = float(result["Predicted_Sales"])
# Display result with enhanced styling
st.markdown(f"""
<div class="prediction-result">
<h2>πŸ“ˆ Prediction Results</h2>
<h1 style="color: #28a745; font-size: 3rem;">${predicted_sales:,.2f}</h1>
<p style="font-size: 1.2rem;">Estimated Monthly Sales Revenue</p>
<p><em>Generated on {datetime.now().strftime('%B %d, %Y at %I:%M %p')}</em></p>
</div>
""", unsafe_allow_html=True)
# Additional insights
st.subheader("πŸ’‘ Insights & Recommendations")
insights_col1, insights_col2 = st.columns(2)
with insights_col1:
if predicted_sales > 2000:
st.success("πŸŽ‰ **High Revenue Potential!** This configuration shows excellent sales prospects.")
elif predicted_sales > 1000:
st.info("πŸ“Š **Moderate Revenue** Expected performance within normal range.")
else:
st.warning("⚠️ **Lower Revenue Forecast** Consider optimizing product or store factors.")
with insights_col2:
# Performance category
if predicted_sales > 2500:
category = "⭐ Excellent"
elif predicted_sales > 1500:
category = "πŸ‘ Good"
elif predicted_sales > 800:
category = "πŸ“ˆ Average"
else:
category = "πŸ“‰ Below Average"
st.metric("Performance Category", category)
# Store results in session state for analytics
if 'predictions' not in st.session_state:
st.session_state.predictions = []
st.session_state.predictions.append({
'timestamp': datetime.now(),
'predicted_sales': predicted_sales,
'configuration': product_data.copy()
})
else:
st.error(f"❌ **API Error** (Status: {response.status_code})")
st.error("Please verify input values or try again later.")
except requests.exceptions.Timeout:
st.error("⏰ **Request Timeout** - The prediction service is taking too long to respond.")
except requests.exceptions.ConnectionError:
st.error("🌐 **Connection Error** - Unable to reach the prediction service.")
except Exception as e:
st.error(f"⚠️ **Unexpected Error**: {str(e)}")
with tab2:
st.subheader("πŸ“Š Analytics Dashboard")
if 'predictions' in st.session_state and st.session_state.predictions:
df = pd.DataFrame([
{
'Timestamp': pred['timestamp'],
'Predicted Sales': pred['predicted_sales'],
'Product Weight': float(pred['configuration']['Product_Weight']),
'MRP': float(pred['configuration']['Product_MRP']),
'Store Age': int(pred['configuration']['Store_Age_Years'])
}
for pred in st.session_state.predictions
])
# Display recent predictions
st.write("### Recent Predictions")
st.dataframe(df.sort_values('Timestamp', ascending=False), use_container_width=True)
# Create visualizations
if len(df) > 1:
col1, col2 = st.columns(2)
with col1:
fig1 = px.line(df, x='Timestamp', y='Predicted Sales',
title='Sales Predictions Over Time')
st.plotly_chart(fig1, use_container_width=True)
with col2:
fig2 = px.scatter(df, x='MRP', y='Predicted Sales',
size='Product Weight', title='Sales vs MRP')
st.plotly_chart(fig2, use_container_width=True)
# Clear history button
if st.button("πŸ—‘οΈ Clear Prediction History"):
st.session_state.predictions = []
st.rerun()
else:
st.info("πŸ“ Generate some predictions first to see analytics here!")
with tab3:
st.subheader("ℹ️ About This Application")
st.markdown("""
### 🎯 Purpose
This application uses machine learning to predict monthly sales revenue for SuperKart retail stores based on product and store characteristics.
### πŸ”§ How It Works
1. **Data Input**: Enter product attributes and store characteristics
2. **ML Processing**: Advanced algorithms analyze the input features
3. **Prediction**: Generate accurate sales revenue forecasts
4. **Insights**: Receive actionable recommendations
### πŸ“Š Key Features
- **Real-time Predictions**: Instant ML-powered forecasting
- **Interactive Interface**: User-friendly input controls
- **Visual Analytics**: Charts and trend analysis
- **Performance Insights**: Automated recommendations
### πŸ› οΈ Technical Details
- **Backend**: HuggingFace Spaces API
- **Model**: Trained on historical SuperKart sales data
- **Accuracy**: Optimized for retail revenue prediction
- **Response Time**: < 3 seconds average
### πŸ“ Usage Notes
- All monetary values are in USD ($)
- Predictions are for monthly revenue estimates
- Results may vary based on market conditions
- For best accuracy, use realistic input values
""")
# Add download button for prediction history
if 'predictions' in st.session_state and st.session_state.predictions:
df_download = pd.DataFrame(st.session_state.predictions)
csv = df_download.to_csv(index=False)
st.download_button(
label="πŸ“₯ Download Prediction History",
data=csv,
file_name=f"superkart_predictions_{datetime.now().strftime('%Y%m%d')}.csv",
mime="text/csv"
)