Spaces:
Sleeping
Sleeping
| import numpy as np | |
| import joblib | |
| import pandas as pd | |
| from flask import Flask, request, jsonify | |
| # Initialize the Flask application | |
| super_kart_api = Flask("Super Kart Price Predictor") | |
| # Load the trained machine learning model | |
| model_path = "backend_files/super_kart_model_v1_0.joblib" | |
| try: | |
| model = joblib.load(model_path) | |
| print(f"Model loaded successfully from {model_path}") | |
| except FileNotFoundError: | |
| raise FileNotFoundError(f"Model file not found at {model_path}. Ensure it's included in the deployment.") | |
| # Define a route for the home page (GET request) | |
| def home(): | |
| """ | |
| This function handles GET requests to the root URL ('/') of the API. | |
| It returns a simple welcome message. | |
| """ | |
| return "Welcome to the Super Kart Price Prediction API!" | |
| # Define an endpoint for single product sales prediction (POST request) | |
| def predict_sales(): | |
| """ | |
| This function handles POST requests to the '/v1/sales' endpoint. | |
| It expects a JSON payload containing product and store details and returns | |
| the predicted sales total as a JSON response. | |
| """ | |
| # Get the JSON data from the request body | |
| input_data = request.get_json() | |
| # Extract relevant features from the JSON data | |
| sample = { | |
| 'Product_Weight': input_data['Product_Weight'], | |
| 'Product_Sugar_Content': input_data['Product_Sugar_Content'], | |
| 'Product_Allocated_Area': input_data['Product_Allocated_Area'], | |
| 'Product_Type': input_data['Product_Type'], | |
| 'Product_MRP': input_data['Product_MRP'], | |
| 'Store_Establishment_Year': input_data['Store_Establishment_Year'], | |
| 'Store_Size': input_data['Store_Size'], | |
| 'Store_Location_City_Type': input_data['Store_Location_City_Type'], | |
| 'Store_Type': input_data['Store_Type'] | |
| } | |
| # Convert to DataFrame | |
| features_df = pd.DataFrame([sample]) | |
| # Apply one-hot encoding | |
| features_df = pd.get_dummies(features_df, columns=['Product_Type', 'Store_Type'], drop_first=True) | |
| # Apply ordinal encoding | |
| sugar_mapping = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2} | |
| size_mapping = {'Small': 0, 'Medium': 1, 'High': 2} | |
| city_mapping = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2} | |
| features_df['Product_Sugar_Content'] = features_df['Product_Sugar_Content'].map(sugar_mapping) | |
| features_df['Store_Size'] = features_df['Store_Size'].map(size_mapping) | |
| features_df['Store_Location_City_Type'] = features_df['Store_Location_City_Type'].map(city_mapping) | |
| # Make prediction | |
| predicted_sales = model.predict(features_df)[0] | |
| predicted_sales = round(float(predicted_sales), 2) | |
| # Return the predicted sales total | |
| return jsonify({'Predicted Sales Total (in dollars)': predicted_sales}) | |
| # Run the app (for testing locally) | |
| if __name__ == '__main__': | |
| super_kart_api.run(debug=True) | |
| # %%writefile backend_files/app.py | |
| # # Import necessary libraries | |
| # import numpy as np | |
| # import joblib # For loading the serialized model | |
| # import pandas as pd # For data manipulation | |
| # from flask import Flask, request, jsonify # For creating the Flask API | |
| # # Initialize the Flask application | |
| # super_kart_api = Flask("Super Kart Price Predictor") | |
| # # Load the trained machine learning model (updated path to match deployment structure) | |
| # model_path = "super_kart_model_v1_0.joblib" | |
| # try: | |
| # model = joblib.load(model_path) | |
| # print(f"Model loaded successfully from {model_path}") | |
| # except FileNotFoundError: | |
| # raise FileNotFoundError(f"Model file not found at {model_path}. Ensure it's included in the deployment.") | |
| # # Define a route for the home page (GET request) | |
| # @super_kart_api.get('/') | |
| # def home(): | |
| # """ | |
| # This function handles GET requests to the root URL ('/') of the API. | |
| # It returns a simple welcome message. | |
| # """ | |
| # return "Welcome to the Super Kart Price Prediction API!" | |
| # # Define an endpoint for single product sales prediction (POST request) | |
| # @super_kart_api.post('/v1/sales') | |
| # def predict_sales(): | |
| # """ | |
| # This function handles POST requests to the '/v1/sales' endpoint. | |
| # It expects a JSON payload containing product and store details and returns | |
| # the predicted sales total as a JSON response. | |
| # """ | |
| # # Get the JSON data from the request body | |
| # input_data = request.get_json() | |
| # # Extract relevant features from the JSON data | |
| # # Note: Exclude Product_Id and Store_Id if they are not used in prediction | |
| # sample = { | |
| # 'Product_Weight': input_data['Product_Weight'], | |
| # 'Product_Sugar_Content': input_data['Product_Sugar_Content'], | |
| # 'Product_Allocated_Area': input_data['Product_Allocated_Area'], | |
| # 'Product_Type': input_data['Product_Type'], | |
| # 'Product_MRP': input_data['Product_MRP'], | |
| # 'Store_Establishment_Year': input_data['Store_Establishment_Year'], | |
| # 'Store_Size': input_data['Store_Size'], | |
| # 'Store_Location_City_Type': input_data['Store_Location_City_Type'], | |
| # 'Store_Type': input_data['Store_Type'] | |
| # } | |
| # # Convert the extracted data into a Pandas DataFrame | |
| # features_df = pd.DataFrame([sample]) | |
| # # Apply one-hot encoding for nominal columns (matching training) | |
| # features_df = pd.get_dummies(features_df, columns=['Product_Type', 'Store_Type'], drop_first=True) | |
| # # Apply ordinal encoding (based on provided orders) | |
| # sugar_mapping = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2} | |
| # size_mapping = {'Small': 0, 'Medium': 1, 'High': 2} | |
| # city_mapping = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2} | |
| # features_df['Product_Sugar_Content'] = features_df['Product_Sugar_Content'].map(sugar_mapping) | |
| # features_df['Store_Size'] = features_df['Store_Size'].map(size_mapping) | |
| # features_df['Store_Location_City_Type'] = features_df['Store_Location_City_Type'].map(city_mapping) | |
| # # Make prediction (assuming direct sales prediction; adjust if log-transformed) | |
| # predicted_sales = model.predict(features_df)[0] | |
| # # If your model predicts log(sales), uncomment and use this instead: | |
| # # predicted_log_sales = model.predict(features_df)[0] | |
| # # predicted_sales = np.exp(predicted_log_sales) | |
| # # Convert to Python float and round to 2 decimals | |
| # predicted_sales = round(float(predicted_sales), 2) | |
| # # Return the predicted sales total | |
| # return jsonify({'Predicted Sales Total (in dollars)': predicted_sales}) | |
| # # Run the app (for testing locally; remove or adjust for production) | |
| # if __name__ == '__main__': | |
| # super_kart_api.run(debug=True) | |