Lokiiparihar commited on
Commit
3fd5ae7
·
verified ·
1 Parent(s): b673b3d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -72
app.py CHANGED
@@ -1,72 +1,58 @@
1
- import re
2
- import streamlit as st
3
- import pandas as pd
4
- import joblib
5
-
6
- # Load trained model
7
- MODEL_PATH = "superkart_sales_prediction_model_v1_0.joblib"
8
- model = joblib.load(MODEL_PATH)
9
-
10
- valid_store_ids = ["OUT001", "OUT002", "OUT003", "OUT004"]
11
- store_meta = {
12
- "OUT001": {"year": 1987, "size": "High", "city_type": "Tier 2", "store_type": "Supermarket Type1"},
13
- "OUT002": {"year": 1998, "size": "Small", "city_type": "Tier 3", "store_type": "Food Mart"},
14
- "OUT003": {"year": 1999, "size": "Medium", "city_type": "Tier 1", "store_type": "Departmental Store"},
15
- "OUT004": {"year": 2009, "size": "Medium", "city_type": "Tier 2", "store_type": "Supermarket Type2"},
16
- }
17
-
18
- st.title("SmartKart: Product Sales Prediction")
19
- st.subheader("Online Prediction")
20
-
21
- # Product ID validation
22
- product_id = st.text_input("Product ID (2 uppercase letters + 4 digits, e.g., FD6114)", max_chars=6)
23
- product_id_valid = bool(re.fullmatch(r"[A-Z]{2}\d{4}", product_id))
24
- if product_id and not product_id_valid:
25
- st.error("Invalid Product ID format; it must be 2 uppercase letters followed by 4 digits.")
26
- elif product_id_valid:
27
- st.success("Product ID format is valid.")
28
-
29
- # Store selection
30
- store_id = st.selectbox("Store ID", options=valid_store_ids)
31
- meta = store_meta[store_id]
32
- st.text(f"Store Establishment Year: {meta['year']}")
33
- st.text(f"Store Size: {meta['size']}")
34
- st.text(f"Store Location City Type: {meta['city_type']}")
35
- st.text(f"Store Type: {meta['store_type']}")
36
-
37
- # Product features
38
- product_weight = st.number_input("Product Weight", min_value=0.0, value=12.0, format="%.2f")
39
- product_sugar_content = st.selectbox("Product Sugar Content", ["Low Sugar", "Regular", "No Sugar"])
40
- product_allocated_area = st.slider("Product Allocated Area Ratio", min_value=0.0, max_value=1.0, step=0.001, value=0.05)
41
- product_type = st.selectbox("Product Type", [
42
- "Meat", "Snack Foods", "Hard Drinks", "Dairy", "Canned", "Soft Drinks",
43
- "Health and Hygiene", "Baking Goods", "Bread", "Breakfast", "Frozen Foods",
44
- "Fruits and Vegetables", "Household", "Seafood", "Starchy Foods", "Others"
45
- ])
46
- product_mrp = st.number_input("Product MRP", min_value=0.0, value=150.0, format="%.2f")
47
-
48
- # Prepare dataframe
49
- input_data = pd.DataFrame([{
50
- "Product_Id": product_id,
51
- "Product_Weight": product_weight,
52
- "Product_Sugar_Content": product_sugar_content,
53
- "Product_Allocated_Area": product_allocated_area,
54
- "Product_Type": product_type,
55
- "Product_MRP": product_mrp,
56
- "Store_Id": store_id,
57
- "Store_Establishment_Year": meta['year'],
58
- "Store_Size": meta['size'],
59
- "Store_Location_City_Type": meta['city_type'],
60
- "Store_Type": meta['store_type'],
61
- }])
62
-
63
- # Prediction
64
- if st.button("Predict"):
65
- if not product_id_valid:
66
- st.error("Please fix the Product ID before proceeding.")
67
- else:
68
- try:
69
- prediction = model.predict(input_data)[0]
70
- st.success(f"Predicted Product Sales: {prediction:.2f}")
71
- except Exception as e:
72
- st.error(f"Prediction failed: {e}")
 
1
+ # Import necessary libraries
2
+ import numpy as np
3
+ import joblib # For loading the serialized model
4
+ import pandas as pd # For data manipulation
5
+ from flask import Flask, request, jsonify # For creating the Flask API
6
+
7
+ # Initialize the Flask application
8
+ sales_predictor_api = Flask("Superkart Sales Predictor")
9
+
10
+ # Load the trained machine learning model
11
+ model = joblib.load("superkart_pred_model_v1_0.joblib")
12
+
13
+ # Define a route for the home page (GET request)
14
+ @sales_predictor_api.get('/')
15
+ def home():
16
+ """
17
+ This function handles GET requests to the root URL ('/') of the API.
18
+ It returns a simple welcome message.
19
+ """
20
+ return "Welcome to the Superkart Sales Prediction API!"
21
+
22
+ # Define an endpoint for single property prediction (POST request)
23
+ @sales_predictor_api.post('/v1/sales')
24
+ def predict_sales():
25
+ """
26
+ This function handles POST requests to the '/v1/sales' endpoint.
27
+ It expects a JSON payload containing property details and returns
28
+ the predicted sales as a JSON response.
29
+ """
30
+ # Get the JSON data from the request body
31
+ property_data = request.get_json()
32
+
33
+
34
+ # Extract relevant features from the JSON data
35
+ sample = {
36
+ 'Product_Weight': property_data['Product_Weight'],
37
+ 'Product_Sugar_Content': property_data['Product_Sugar_Content'],
38
+ 'Product_Allocated_Area': property_data['Product_Allocated_Area'],
39
+ 'Product_Type': property_data['Product_Type'],
40
+ 'Product_MRP': property_data['Product_MRP'],
41
+ 'Store_Id': property_data['Store_Id'],
42
+ 'Store_Establishment_Year': property_data['Store_Establishment_Year'],
43
+ 'Store_Size': property_data['Store_Size'],
44
+ 'Store_Type': property_data['Store_Type']
45
+ }
46
+
47
+ # Convert the extracted data into a Pandas DataFrame
48
+ input_data = pd.DataFrame([sample])
49
+
50
+ # Make prediction (get log_price)
51
+ predicted_sales = model.predict(input_data)[0]
52
+
53
+ # Return the actual price
54
+ return jsonify({'Predicted Sales (in dollars)': predicted_sales})
55
+
56
+ # Run the Flask application in debug mode if this script is executed directly
57
+ if __name__ == '__main__':
58
+ sales_predictor_api.run(debug=True)