# Import necessary libraries import numpy as np import joblib # For loading the serialized model import pandas as pd # For data manipulation import os from flask import Flask, request, jsonify # For creating the Flask API # Initialize the Flask application revenue_predictor_api = Flask("Revenue Predictor") # Load the trained machine learning model #model = joblib.load("revenue_prediction_model_v1_0.joblib") model = joblib.load(os.path.join(os.path.dirname(__file__), "revenue_prediction_model_v1_0.joblib")) print("Model loaded successfully!") # Define a route for the home page (GET request) @revenue_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 Revenue Prediction API!" # Define an endpoint for single product revenue prediction (POST request) @revenue_predictor_api.post('/v1/revenue') def predict_revenue(): """ This function handles POST requests to the '/v1/revenue' endpoint. It expects a JSON payload containing property details and returns the predicted rental price as a JSON response. """ # Get the JSON data from the request body property_data = request.get_json() # Extract relevant features from the JSON data sample = { 'Product_Weight': property_data['Product_Weight'], 'Product_Sugar_Content': property_data['Product_Sugar_Content'], 'Product_Allocated_Area': property_data['Product_Allocated_Area'], 'Product_Type': property_data['Product_Type'], 'Product_MRP': property_data['Product_MRP'], 'Store_Id': property_data['Store_Id'], 'Store_Establishment_Year': property_data['Store_Establishment_Year'], 'Store_Size': property_data['Store_Size'], 'Store_Location_City_Type': property_data['Store_Location_City_Type'], 'Store_Type': property_data['Store_Type'] } # Convert the extracted data into a Pandas DataFrame input_data = pd.DataFrame([sample]) # Make prediction (get sales_total) predicted_sales_total = model.predict(input_data)[0] # Calculate actual sales predicted_total = np.exp(predicted_sales_total) # Convert predicted_total to Python float predicted_total = round(float(predicted_total), 2) # The conversion above is needed as we convert the model prediction (sales_total) to actual sales using np.exp, which returns predictions as NumPy float32 values. # When we send this value directly within a JSON response, Flask's jsonify function encounters a datatype error # Return the actual sales return jsonify({'Predicted Sales Total (in dollars)': predicted_total}) # Run the Flask application in debug mode if this script is executed directly if __name__ == '__main__': #revenue_predictor_api.run(debug=True) port = int(os.environ.get("PORT", 7860)) # Hugging Face provides PORT revenue_predictor_api.run(host="0.0.0.0", port=port, debug=True)