import joblib import pandas as pd from flask import Flask, request, jsonify # Initialize Flask app with a name sales_predictor_api = Flask("Superkart Sales Predictor") # Load the trained sales prediction model model = joblib.load("superkart_price_prediction_model_v1_0.joblib") # Define a route for the home page @sales_predictor_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 Superkart Sales Price Prediction API!" # Define an endpoint to predict sales for a product @sales_predictor_api.post('/v1/sales') def predict_sales(): # Get JSON data from the request sales_data = request.get_json() # Extract relevant superkart features from the input data sample = { 'Product_Weight': sales_data['Product_Weight'], 'Product_Allocated_Area': sales_data['Product_Allocated_Area'], 'Product_MRP': sales_data['Product_MRP'], 'Store_Establishment_Year': sales_data['Store_Establishment_Year'], 'Product_Sugar_Content': sales_data['Product_Sugar_Content'], 'Product_Type': sales_data['Product_Type'], 'Store_Size': sales_data['Store_Size'], 'Store_Location_City_Type': sales_data['Store_Location_City_Type'], 'Store_Type': sales_data['Store_Type'] } # Convert the extracted data into a Pandas DataFrame input_data = pd.DataFrame([sample]) # Calculate actual price predicted_price = model.predict(input_data)[0] # Convert predicted_price to Python float predicted_price = round(float(predicted_price), 2) # Return the actual price return jsonify({'Sales Prediction Price (in dollars)': predicted_price}) # Define an endpoint to predict sales for a batch of multiple products @sales_predictor_api.post('/v1/salesbatch') def predict_sales_price_batch(): """ This function handles POST requests to the '/v1/salesbatch' endpoint. It expects a CSV file containing saleskart details for multiple products and returns the predicted sales prices 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) # Make predictions for all products in the DataFrame predicted_sales_prices = model.predict(input_data).tolist() # Calculate actual prices rounded to 2 DCM predicted_prices = [round(float(sales_price), 2) for sales_price in predicted_sales_prices] # Create a dictionary of predictions with Product IDs as keys product_ids = input_data['id'].tolist() # Assuming 'id' is the property ID column output_dict = dict(zip(product_ids, predicted_prices)) # Use actual prices # Return the predictions dictionary as a JSON response return output_dict # Run the Flask application in debug mode if this script is executed directly if __name__ == '__main__': sales_predictor_api.run(debug=True)