File size: 4,482 Bytes
e47468d
 
 
4f57fd2
e47468d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f57fd2
e47468d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import streamlit as st
import pandas as pd
import requests
import numpy as np # Import numpy here for log1p calculation

# Set the title of the Streamlit app
st.title("🛒 SuperKart Sales Total Predictor")
st.markdown("Forecasting product sales based on product characteristics and store type.")

# --- API Endpoint Configuration (Replace placeholders with your actual Space URL) ---
# NOTE: Replace <username>-<repo_id> with the actual ID of your Hugging Face Space.
API_BASE_URL = "https://Tamilvelan-StoreSalesPredictionBackend.hf.space"
ONLINE_PREDICTION_URL = f"{API_BASE_URL}/v1/sales"
# -----------------------------------------------------------------------------------


# Section for online prediction
st.subheader("Predict Single Product-Store Sales")

# --- Collect user input for SuperKart features ---

# Numerical and Engineered Features
col1, col2 = st.columns(2)
with col1:
    product_weight = st.number_input("Product Weight (kg)", min_value=1.0, max_value=25.0, value=12.02, step=0.01)
    product_mrp = st.number_input("Product MRP ($)", min_value=10.0, max_value=300.0, value=141.6, step=0.01)
    store_age = st.number_input("Store Age (Years)", min_value=1, max_value=50, value=25, help="Calculated as (Current Year - Store Establishment Year)")
    
with col2:
    # Categorical Features (We assume the input still needs the RAW categorical feature for the full Pipeline to work)
    product_sugar_content = st.selectbox("Product Sugar Content", ["Low Sugar", "Regular", "No Sugar"])
    product_type = st.selectbox("Product Type", ['Fruits and Vegetables', 'Snack Foods', 'Soft Drinks', 'Dairy', 'Baking Goods', 'Household', 'Others', 'Meat', 'Frozen Foods', 'Breakfast', 'Canned', 'Starchy Foods', 'Health and Hygiene', 'Fats and Oils', 'Seafood'])
    store_type = st.selectbox("Store Type", ['Supermarket Type 1', 'Departmental Store', 'Supermarket Type 2', 'Food Mart'])

# Ordinal Encoded Features (Using the user-friendly category, but mapping to the expected ENCODED value)
# NOTE: The Backend API assumes it receives the ENCODED value (0, 1, 2, 3), not the raw string!
store_size_map = {"Low": 0, "Medium": 1, "High": 2}
store_city_map = {"Tier 3": 1, "Tier 2": 2, "Tier 1": 3}

store_size_raw = st.selectbox("Store Size", list(store_size_map.keys()))
store_location_city_type_raw = st.selectbox("Store Location City Type", list(store_city_map.keys()))

# --- Special Engineered Input for Allocated Area Log ---
# Since the model expects a LOG-TRANSFORMED value, we must either:
# 1. Ask the user for the raw value and perform log1p here (cleaner)
# 2. Ask the user for the log value (less intuitive)

# We will ask for the raw value and transform it before sending to the API
product_allocated_area_raw = st.number_input("Product Allocated Area (Raw Value)", min_value=0.0, value=0.05, step=0.01)
product_allocated_area_log = float(np.log1p(product_allocated_area_raw)) # Calculate log1p(x)

# --- Prepare Data Payload ---


# Convert user input into a dictionary matching the API's expected JSON structure
input_payload = {
    'Product_Weight': product_weight,
    'Product_MRP': product_mrp,
    'Store_Age': store_age,
    'Product_Allocated_Area_Log': product_allocated_area_log,
    
    # Send the encoded integer values for ordinal features as the API expects them
    'Store_Size_Encoded': store_size_map[store_size_raw],
    'Store_Location_City_Type_Encoded': store_city_map[store_location_city_type_raw],
    
    # Send the raw string values for nominal features (assuming the model pipeline handles OHE)
    'Product_Sugar_Content': product_sugar_content,
    'Product_Type': product_type,
    'Store_Type': store_type,
}


# Make prediction when the "Predict" button is clicked
if st.button("Predict Sales Total"):
    try:
        # Send data to Flask API
        response = requests.post(ONLINE_PREDICTION_URL, json=input_payload) 
        
        if response.status_code == 200:
            prediction = response.json().get('Predicted Sales Total (in dollars)')
            if prediction is not None:
                st.success(f"Predicted Product Sales Total: **${prediction:,.2f}**")
            else:
                st.error("Prediction key not found in API response.")
        else:
            st.error(f"Error making prediction. Status code: {response.status_code}. Response: {response.text}")
    except requests.exceptions.RequestException as e:
        st.error(f"An error occurred while connecting to the API: {e}")