hkbindhu commited on
Commit
ecdda5d
·
verified ·
1 Parent(s): 4f6bc6c

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +64 -92
  2. requirements.txt +3 -9
app.py CHANGED
@@ -1,92 +1,64 @@
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
- superkart_sales_predictor_api = Flask("SuperKart Sales Predictor")
9
-
10
- # Load the trained machine learning model
11
- model = joblib.load("super_kart_prediction_model_v1_0.joblib")
12
-
13
- # Define a route for the home page (GET request)
14
- @superkart_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 Super Kart Sales Prediction API!"
21
-
22
- # Define an endpoint for single property prediction (POST request)
23
- @superkart_sales_predictor_api.post('/v1/sales')
24
- def predict_sales_total():
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 rental price as a JSON response.
29
- """
30
- # Get the JSON data from the request body
31
- property_data = request.get_json()
32
-
33
- # Extract relevant features from the JSON data
34
- sample = {
35
- 'Product_Weight': property_data['Product_Weight'],
36
- 'Product_Allocated_Area': property_data['Product_Allocated_Area'],
37
- 'Product_MRP': property_data['Product_MRP'],
38
- 'Store_Establishment_Year': property_data['Store_Establishment_Year'],
39
- 'Product_Sugar_Content': property_data['Product_Sugar_Content'],
40
- 'Product_Type': property_data['Product_Type'],
41
- 'Store_Size': property_data['Store_Size'],
42
- 'Store_Location_City_Type': property_data['Store_Location_City_Type'],
43
- 'Store_Type': property_data['Store_Type']
44
- }
45
- # Convert the extracted data into a Pandas DataFrame
46
- input_data = pd.DataFrame([sample])
47
-
48
- # Make prediction (get Product_Store_Sales_Total)
49
- predicted_product_store_sales_total = model.predict(input_data)[0]
50
-
51
- # Calculate sales total
52
- predicted_sales_total = np.exp(predicted_product_store_sales_total)
53
-
54
- # Convert predicted_sales_total to Python float
55
- predicted_sales_total = round(float(predicted_sales_total), 2)
56
- # The conversion above is needed as we convert the model prediction (Product_Store_Sales_Total) to actual sales using np.exp, which returns predictions as NumPy float32 values.
57
- # When we send this value directly within a JSON response, Flask's jsonify function encounters a datatype error
58
-
59
- # Return the actual Sales Total
60
- return jsonify({'Predicted Sales Total (in dollars)': predicted_sales_total})
61
-
62
-
63
- # Define an endpoint for batch prediction (POST request)
64
- @superkart_sales_predictor_api.post('/v1/salesbatch')
65
- def superkart_sales_batch():
66
- """
67
- This function handles POST requests to the '/v1/salesbatch' endpoint.
68
- It expects a CSV file containing property details for multiple properties
69
- and returns the predicted sales list as a dictionary in the JSON response.
70
- """
71
- # Get the uploaded CSV file from the request
72
- file = request.files['file']
73
-
74
- # Read the CSV file into a Pandas DataFrame
75
- input_data = pd.read_csv(file)
76
-
77
- # Make predictions for all properties in the DataFrame (get Product_Store_Sales_Total)
78
- predicted_product_store_sales_total = model.predict(input_data).tolist()
79
-
80
- # Calculate actual prices
81
- predicted_sales_total = [round(float(np.exp(Product_Store_Sales_Total)), 2) for Product_Store_Sales_Total in predicted_product_store_sales_total]
82
-
83
- # Create a dictionary of predictions with property IDs as keys
84
- property_ids = input_data['id'].tolist() # Assuming 'id' is the property ID column
85
- output_dict = dict(zip(property_ids, predicted_sales_total)) # Use actual prices
86
-
87
- # Return the predictions dictionary as a JSON response
88
- return output_dict
89
-
90
- # Run the Flask application in debug mode if this script is executed directly
91
- if __name__ == '__main__':
92
- superkart_sales_predictor_api.run(debug=True)
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import requests
4
+
5
+ # Set the title of the Streamlit app
6
+ st.title("Super Kart Store Total Sale Prediction")
7
+
8
+ # Section for online prediction
9
+ st.subheader("Online Prediction")
10
+
11
+ # Collect user input for property features
12
+ Product_Weight = st.number_input("Product Weight", min_value=4.0, max_value=22.0, step=0.1, value=10.0)
13
+ Product_Allocated_Area = st.number_input("Product Allocated Area", min_value=0.004, max_value=0.298, step=0.01, value=0.22)
14
+ Product_MRP = st.number_input("Product MRP", min_value=31.0, max_value=266.0, step=0.5, value=10.0)
15
+ Store_Establishment_Year = st.selectbox("Store Establishment Year", [1987, 1998, 1999, 2009])
16
+ Product_Sugar_Content = st.selectbox("Product Sugar Content", ["Low Sugar", "Regular", "No Sugar"])
17
+ Product_Type = st.selectbox("Product Type", [
18
+ "Fruits and Vegetables", "Snack Foods", "Frozen Foods", "Dairy", "Household", "Baking Goods", "Canned",
19
+ "Health and Hygiene", "Meat", "Soft Drinks", "Breads", "Hard Drinks", "Starchy Foods", "Breakfast", "Seafood", "Others"
20
+ ])
21
+ Store_Size = st.selectbox("Store Size", ["Medium", "High", "Small"])
22
+ Store_Location_City_Type = st.selectbox("Store Location City Type", ["Tier 1", "Tier 2", "Tier 3"])
23
+ Store_Type = st.selectbox("Store Type", [
24
+ "Departmental Store", "Food Mart", "Supermarket Type1", "Supermarket Type2"
25
+ ])
26
+
27
+ # Convert user input into a DataFrame
28
+ input_data = pd.DataFrame([{
29
+ 'Product_Weight': Product_Weight,
30
+ 'Product_Allocated_Area': Product_Allocated_Area,
31
+ 'Product_MRP': Product_MRP,
32
+ 'Store_Establishment_Year': Store_Establishment_Year,
33
+ 'Product_Sugar_Content': Product_Sugar_Content,
34
+ 'Product_Type': Product_Type
35
+ 'Store_Size': Store_Size,
36
+ 'Store_Location_City_Type': Store_Location_City_Type,
37
+ 'Store_Type': Store_Type
38
+ }])
39
+
40
+ # Make prediction when the "Predict" button is clicked
41
+ if st.button("Predict"):
42
+ response = requests.post("https://hkbindhu-superkart.hf.space/v1/sales", json=input_data.to_dict(orient='records')[0]) # Send data to Flask API
43
+ if response.status_code == 200:
44
+ prediction = response.json()['Predicted Sales Total (in dollars)']
45
+ st.success(f"Predicted Sales Total (in dollars): {prediction}")
46
+ else:
47
+ st.error("Error making prediction.")
48
+
49
+ # Section for batch prediction
50
+ st.subheader("Batch Prediction")
51
+
52
+ # Allow users to upload a CSV file for batch prediction
53
+ uploaded_file = st.file_uploader("Upload CSV file for batch prediction", type=["csv"])
54
+
55
+ # Make batch prediction when the "Predict Batch" button is clicked
56
+ if uploaded_file is not None:
57
+ if st.button("Predict Batch"):
58
+ response = requests.post("https://hkbindhu-superkart.hf.space/v1/salesbatch", files={"file": uploaded_file}) # Send file to Flask API
59
+ if response.status_code == 200:
60
+ predictions = response.json()
61
+ st.success("Batch predictions completed!")
62
+ st.write(predictions) # Display the predictions
63
+ else:
64
+ st.error("Error making batch prediction.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,11 +1,5 @@
1
  pandas==2.2.2
2
- numpy==2.0.2
3
- scikit-learn==1.6.1
4
- xgboost==2.1.4
5
- joblib==1.4.2
6
- Werkzeug==2.2.2
7
- flask==2.2.2
8
- gunicorn==20.1.0
9
  requests==2.28.1
10
- uvicorn[standard]
11
- streamlit==1.43.2
 
 
1
  pandas==2.2.2
 
 
 
 
 
 
 
2
  requests==2.28.1
3
+ streamlit
4
+ numpy
5
+ flask