Spaces:
Sleeping
Sleeping
| # Import necessary libraries | |
| 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 | |
| superkart_sales_api = Flask("SuperKart Product Store Sales Predictor") | |
| # Load the trained machine learning model | |
| model = joblib.load("SuperKart_model_v1_0.joblib") | |
| # 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 SuperKart Product Store Sales Prediction API!" | |
| # Define an endpoint for single product prediction (POST request) | |
| def predict_product_sales(): | |
| """ | |
| This function handles POST requests to the '/v1/product' endpoint. | |
| It expects a JSON payload containing product and store details and returns | |
| the predicted sales as a JSON response. | |
| """ | |
| # Get the JSON data from the request body | |
| product_data = request.get_json() | |
| # Extract original features from the JSON data | |
| original_features = { | |
| 'Product_Id': product_data['Product_Id'], | |
| 'Product_Weight': product_data['Product_Weight'], | |
| 'Product_Sugar_Content': product_data['Product_Sugar_Content'], | |
| 'Product_Allocated_Area': product_data['Product_Allocated_Area'], | |
| 'Product_Type': product_data['Product_Type'], | |
| 'Product_MRP': product_data['Product_MRP'], | |
| 'Store_Id': product_data['Store_Id'], | |
| 'Store_Establishment_Year': product_data['Store_Establishment_Year'], | |
| 'Store_Size': product_data['Store_Size'], | |
| 'Store_Location_City_Type': product_data['Store_Location_City_Type'], | |
| 'Store_Type': product_data['Store_Type'] | |
| } | |
| # Convert to DataFrame to easily calculate engineered features | |
| input_data = pd.DataFrame([original_features]) | |
| # Calculate engineered features | |
| current_year = pd.to_datetime('now').year | |
| input_data['Store_Age'] = current_year - input_data['Store_Establishment_Year'] | |
| perishables = ['Fruits and Vegetables', 'Dairy', 'Meat', 'Seafood', 'Breads', 'Breakfast'] | |
| input_data['Product_Category_Type'] = input_data['Product_Type'].apply(lambda x: 'Perishables' if x in perishables else 'Non Perishables') | |
| # Assuming Product_Id is in the format 'XX####' and we need the first two characters | |
| input_data['Product_Category_from_ID'] = input_data['Product_Id'].apply(lambda x: x[:2]) | |
| # Make prediction and round to 2 decimal places | |
| prediction = round(model.predict(input_data).tolist()[0], 2) | |
| # Return the prediction as a JSON response | |
| return jsonify({'Predicted_Product_Store_Sales_Total': prediction}) | |
| # Define an endpoint for batch prediction (POST request) | |
| def predict_product_batch(): | |
| """ | |
| This function handles POST requests to the '/v1/productbatch' endpoint. | |
| It expects a CSV file containing product and store details for multiple entries | |
| and returns the predicted sales as a dictionary in the JSON response. | |
| """ | |
| # Get the uploaded CSV file from the request | |
| file = request.files['file'] | |
| # Read the CSV file into a Pandas DataFrame | |
| input_data = pd.read_csv(file) | |
| # Calculate engineered features for batch prediction | |
| current_year = pd.to_datetime('now').year | |
| input_data['Store_Age'] = current_year - input_data['Store_Establishment_Year'] | |
| perishables = ['Fruits and Vegetables', 'Dairy', 'Meat', 'Seafood', 'Breads', 'Breakfast'] | |
| input_data['Product_Category_Type'] = input_data['Product_Type'].apply(lambda x: 'Perishables' if x in perishables else 'Non Perishables') | |
| # Assuming Product_Id is in the format 'XX####' and we need the first two characters | |
| input_data['Product_Category_from_ID'] = input_data['Product_Id'].apply(lambda x: x[:2]) | |
| # Make predictions for the batch data and round to 2 decimal places | |
| predictions = [round(pred, 2) for pred in model.predict(input_data).tolist()] | |
| # Add predictions to the DataFrame | |
| input_data['Predicted_Product_Store_Sales_Total'] = predictions | |
| # Convert results to dictionary | |
| result = input_data.to_dict(orient="records") | |
| return jsonify(result) | |
| # Run the Flask application in debug mode if this script is executed directly | |
| if __name__ == '__main__': | |
| superkart_sales_api.run(debug=True) | |