ScottIzi's picture
Upload folder using huggingface_hub
2ea6547 verified
Raw History Blame Contribute Delete
2.77 kB
# Import necessary libraries
import numpy as np
import joblib # For loading the serialized model
import polars as pl # Polars instead of pandas
from flask import Flask, request, jsonify # Flask API
# Initialize Flask app with a name
superkart_api = Flask("SuperKart_API")
# Load trained model pipeline
model = joblib.load("Gradient-Boosting-Regressor-Tuned.joblib")
# Home route
@superkart_api.get('/')
def home():
return "SuperKart Sales Prediction API is running"
# Prediction endpoint
@superkart_api.post('/v1/predict')
def predict_sales():
# Get JSON input
data = request.get_json()
# Extract features
required_fields = [
'Product_Weight',
'Product_Sugar_Content',
'Product_Allocated_Area',
'Product_MRP',
'Store_Size',
'Store_Location_City_Type',
'Store_Type',
'Product_Id_char',
'Store_Age_Years',
'Product_Type_Category'
]
# Check for missing or null values
missing_fields = [
field for field in required_fields
if field not in data or data[field] is None or data[field] == ""
]
# If any field is missing → return error
if missing_fields:
return jsonify({
"error": "Missing or empty fields in request body",
"missing_fields": missing_fields,
"expected_format": {
"Product_Weight": "float",
"Product_Sugar_Content": "string",
"Product_Allocated_Area": "float",
"Product_MRP": "float",
"Store_Size": "string",
"Store_Location_City_Type": "string",
"Store_Type": "string",
"Product_Id_char": "string",
"Store_Age_Years": "float",
"Product_Type_Category": "string"
}
}), 400
# Safe to build sample
sample = {
'Product_Weight': data['Product_Weight'],
'Product_Sugar_Content': data['Product_Sugar_Content'],
'Product_Allocated_Area': data['Product_Allocated_Area'],
'Product_MRP': data['Product_MRP'],
'Store_Size': data['Store_Size'],
'Store_Location_City_Type': data['Store_Location_City_Type'],
'Store_Type': data['Store_Type'],
'Product_Id_char': data['Product_Id_char'],
'Store_Age_Years': data['Store_Age_Years'],
'Product_Type_Category': data['Product_Type_Category']
}
# Convert to Polars DataFrame
input_data = pl.DataFrame([sample])
# Convert to numpy for sklearn compatibility (safe step)
prediction = model.predict(input_data.to_pandas()).tolist()[0]
return jsonify({'Sales': prediction})
# Run app
if __name__ == '__main__':
superkart_api.run(debug=True)