Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041427 unmodified lines5051525354555657585960616263646566676869707172737475import streamlit as stimport requestsimport pandas as pd # Used for displaying data# --- Configuration --- #BACKEND_URL = "https://RoopaST-Sales-Prediction-Backend-1.hf.space/predict" # Corrected to include /predict endpoint# --- Streamlit UI --- #st.set_page_config(page_title="SuperKart Sales Predictor", layout="wide")st.title("🛒 SuperKart Sales Predictor")st.write("Enter product and store details to predict sales revenue.")# --- Input Form --- #with st.form("sales_prediction_form"):st.header("Product Details")product_id = st.text_input("Product ID", "FD6114", help="e.g., FD6114, NC1180")product_weight = st.number_input("Product Weight (kg)", min_value=4.0, max_value=22.0, value=12.66, step=0.01)product_mrp = st.number_input("Product MRP (₹)", min_value=30.0, max_value=270.0, value=117.08, step=0.01)product_allocated_area = st.number_input("Product Allocated Area Ratio", min_value=0.0, max_value=0.2, value=0.027, step=0.001)product_sugar_content = st.selectbox("Product Sugar Content", ['Low Sugar', 'Regular', 'No Sugar'], index=0)product_type = st.selectbox("Product Type", ['Baking Goods', 'Breads', 'Breakfast', 'Canned', 'Dairy', 'Frozen Foods','Fruits and Vegetables', 'Hard Drinks', 'Health and Hygiene', 'Household','Meat', 'Others', 'Seafood', 'Snack Foods', 'Soft Drinks', 'Starchy Foods'], index=6) # Fruits and Vegetables as defaultst.header("Store Details")store_id = st.text_input("Store ID", "OUT004", help="e.g., OUT004, OUT003")store_establishment_year = st.number_input("Store Establishment Year", min_value=1985, max_value=2009, value=2009, step=1)store_size = st.selectbox("Store Size", ['High', 'Medium', 'Small'], index=1)store_location_city_type = st.selectbox("Store Location City Type", ['Tier 1', 'Tier 2', 'Tier 3'], index=1)store_type = st.selectbox("Store Type", ['Departmental Store', 'Food Mart', 'Supermarket Type1', 'Supermarket Type2'], index=3)submitted = st.form_submit_button("Predict Sales")# --- Prediction Logic --- #if submitted:# Create input data dictionary matching the backend's expected raw input formatinput_data = {"Product_Id": product_id,"Product_Weight": product_weight,"Product_Sugar_Content": product_sugar_content,7 unmodified lines"Store_Type": store_type}st.subheader("Input Data Provided:")st.json(input_data)try:response = requests.post(BACKEND_URL, json=input_data)print(f"Response status code: {response.status_code}") # Debugging printresponse.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)prediction = response.json()if "predicted_sales" in prediction:st.success(f"Predicted Product Sales Total: ₹ {prediction['predicted_sales']:.2f}")else:st.error(f"Prediction failed: {prediction.get('error', 'Unknown error from backend')}")except requests.exceptions.ConnectionError:st.error(f"Could not connect to the backend URL: {BACKEND_URL}. Please ensure the backend is running and accessible.")except requests.exceptions.RequestException as e:st.error(f"An error occurred during the API request: {e}. Check backend logs for more details.")except Exception as e:st.error(f"An unexpected error occurred: {e}")st.markdown("---")st.info("Note: This UI connects to a Flask backend deployed on Hugging Face Spaces. Make sure the backend is running.")12345678910111213141516171819202122232425262728293031323334353637383940414243447 unmodified lines525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import streamlit as stimport requestsimport pandas as pd # Used for displaying dataimport json # For parsing JSON input# --- Configuration --- #BACKEND_SINGLE_PREDICT_URL = "https://RoopaST-Sales-Prediction-Backend-1.hf.space/predict"BACKEND_BATCH_PREDICT_URL = "https://RoopaST-Sales-Prediction-Backend-1.hf.space/predict_batch"# --- Streamlit UI --- #st.set_page_config(page_title="SuperKart Sales Predictor", layout="wide")st.title("🛒 SuperKart Sales Predictor")st.write("Enter product and store details to predict sales revenue.")# --- Single Prediction Form ---st.header("Single Prediction")with st.form("single_sales_prediction_form"):st.subheader("Product Details")product_id = st.text_input("Product ID", "FD6114", help="e.g., FD6114, NC1180")product_weight = st.number_input("Product Weight (kg)", min_value=4.0, max_value=22.0, value=12.66, step=0.01)product_mrp = st.number_input("Product MRP (₹)", min_value=30.0, max_value=270.0, value=117.08, step=0.01)product_allocated_area = st.number_input("Product Allocated Area Ratio", min_value=0.0, max_value=0.2, value=0.027, step=0.001)product_sugar_content = st.selectbox("Product Sugar Content", ['Low Sugar', 'Regular', 'No Sugar'], index=0, key='single_sugar')product_type = st.selectbox("Product Type", ['Baking Goods', 'Breads', 'Breakfast', 'Canned', 'Dairy', 'Frozen Foods','Fruits and Vegetables', 'Hard Drinks', 'Health and Hygiene', 'Household','Meat', 'Others', 'Seafood', 'Snack Foods', 'Soft Drinks', 'Starchy Foods'], index=6, key='single_type') # Fruits and Vegetables as defaultst.subheader("Store Details")store_id = st.text_input("Store ID", "OUT004", help="e.g., OUT004, OUT003", key='single_store_id')store_establishment_year = st.number_input("Store Establishment Year", min_value=1985, max_value=2009, value=2009, step=1, key='single_est_year')store_size = st.selectbox("Store Size", ['High', 'Medium', 'Small'], index=1, key='single_store_size')store_location_city_type = st.selectbox("Store Location City Type", ['Tier 1', 'Tier 2', 'Tier 3'], index=1, key='single_city_type')store_type = st.selectbox("Store Type", ['Departmental Store', 'Food Mart', 'Supermarket Type1', 'Supermarket Type2'], index=3, key='single_store_type')submitted_single = st.form_submit_button("Predict Single Sale")# --- Single Prediction Logic ---if submitted_single:input_data_single = {"Product_Id": product_id,"Product_Weight": product_weight,"Product_Sugar_Content": product_sugar_content,7 unmodified lines"Store_Type": store_type}st.subheader("Input Data Provided for Single Prediction:")st.json(input_data_single)try:response = requests.post(BACKEND_SINGLE_PREDICT_URL, json=input_data_single)st.write(f"Backend Response Status Code: {response.status_code}")response.raise_for_status()prediction = response.json()if "predicted_sales" in prediction:st.success(f"Predicted Product Sales Total: {prediction['predicted_sales']:.2f}")else:st.error(f"Prediction failed: {prediction.get('error', 'Unknown error from backend')}")except requests.exceptions.ConnectionError:st.error(f"Could not connect to the backend URL: {BACKEND_SINGLE_PREDICT_URL}. Please ensure the backend is running and accessible.")except requests.exceptions.RequestException as e:st.error(f"An error occurred during the API request: {e}. Check backend logs for more details.")except Exception as e:st.error(f"An unexpected error occurred: {e}")st.markdown("--- --- --- --- --- ")# --- Batch Prediction Form ---st.header("Batch Prediction")st.info("Paste a JSON array of product and store details for multiple predictions. Each object in the array should follow the format for a single prediction.")example_batch_input = '''[{"Product_Id": "FD6114","Product_Weight": 12.66,"Product_Sugar_Content": "Low Sugar","Product_Allocated_Area": 0.027,"Product_Type": "Frozen Foods","Product_MRP": 117.08,"Store_Id": "OUT004","Store_Establishment_Year": 2009,"Store_Size": "Medium","Store_Location_City_Type": "Tier 2","Store_Type": "Supermarket Type2"},{"Product_Id": "NC1180","Product_Weight": 9.57,"Product_Sugar_Content": "No Sugar","Product_Allocated_Area": 0.010,"Product_Type": "Health and Hygiene","Product_MRP": 123.67,"Store_Id": "OUT002","Store_Establishment_Year": 1998,"Store_Size": "Small","Store_Location_City_Type": "Tier 3","Store_Type": "Food Mart"}]'''batch_input_json = st.text_area("JSON Input for Batch Prediction", example_batch_input, height=300)submitted_batch = st.button("Predict Batch Sales")# --- Batch Prediction Logic ---if submitted_batch:try:batch_data_parsed = json.loads(batch_input_json)st.subheader("Batch Input Data Provided:")st.json(batch_data_parsed)response = requests.post(BACKEND_BATCH_PREDICT_URL, json=batch_data_parsed)st.write(f"Backend Response Status Code: {response.status_code}")response.raise_for_status()batch_prediction_results = response.json()if "predicted_sales" in batch_prediction_results:st.success("Batch Predictions:")predictions_df = pd.DataFrame({"Predicted Sales": batch_prediction_results['predicted_sales']})st.dataframe(predictions_df)else:st.error(f"Batch prediction failed: {batch_prediction_results.get('error', 'Unknown error from backend')}")except json.JSONDecodeError:st.error("Invalid JSON format. Please ensure your input is a valid JSON array.")except requests.exceptions.ConnectionError:st.error(f"Could not connect to the backend URL: {BACKEND_BATCH_PREDICT_URL}. Please ensure the backend is running and accessible.")except requests.exceptions.RequestException as e:st.error(f"An error occurred during the API request: {e}. Check backend logs for more details.")except Exception as e:st.error(f"An unexpected error occurred: {e}")st.markdown("--- --- --- --- --- ")st.info("Note: This UI connects to a Flask backend deployed on Hugging Face Spaces. Make sure the backend is running and correctly deployed for both single and batch prediction endpoints.")
app.py+96-26