Varun6299's picture
Upload folder using huggingface_hub
3153b96 verified
from flask import Flask, request, jsonify
import pandas as pd
import joblib # Using pickle for model loading
from sklearn.compose import ColumnTransformer
import traceback
import numpy as np
import os
from typing import Iterable, Optional, Any
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
import joblib
# 💡 CRITICAL: Import your custom class before loading the model
from custom_transformers import ManualProductTypeMapper
# --- Global Model Loading ---
MODEL_PATH = "final_xgboost_pipeline.joblib"
# Initialize the Flask application
superKart_sales_predictor_api = Flask("SuperKart Sales Predictor")
# --- Global Model Loading ---
try:
model = joblib.load(MODEL_PATH)
print("Model loaded successfully.")
except Exception as e:
model = None
print(f"Error loading model: {e}")
# Define a route for the home page
@superKart_sales_predictor_api.get('/')
def home():
print("Home route accessed.") # Add logging
return "Welcome to the SuperKart Store Product Sales Prediction API."
@superKart_sales_predictor_api.post("/predict") # The simple, unversioned route
def predict_sales():
"""
Receives product and store features, makes a sales prediction, and returns the result.
"""
# Get the JSON data from the request body
input_data = request.get_json()
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_Quantity': input_data[ 'Product_Quantity'],
'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
input_data = pd.DataFrame([sample])
# Make prediction (get log_price)
predicted_sales = model.predict(input_data)[0]
# Convert predicted_price to Python float
predicted_sales = round(float(predicted_sales), 2)
# Return the actual price
return jsonify({'Predicted Sales (in dollars)': predicted_sales})
# --- Local Runner (Optional: Comment out for production WSGI) ---
if __name__ == '__main__':
superKart_sales_predictor_api.run(debug=True) # Commented out to prevent blocking in notebook