superkart / app.py
Fair3's picture
Upload folder using huggingface_hub
7e8684a verified
Raw
History Blame Contribute Delete
3.09 kB
import numpy as np
import joblib
import pandas as pd
from flask import Flask, request, jsonify
import os
APP_DIR = os.path.dirname(os.path.abspath(__file__))
# Initialize Flask app
superkart_api = Flask("superkart_predictor")
# Load preprocessor and model
try:
preprocessor_path = os.path.join(APP_DIR, "preprocessor.joblib")
model_path = os.path.join(APP_DIR, "model.joblib")
preprocessor = joblib.load(preprocessor_path)
model = joblib.load(model_path)
print("✅ Preprocessor and model loaded successfully.")
except Exception as e:
print(f"❌ Error loading artifacts: {e}")
preprocessor = None
model = None
# Define a route for the home page
@superkart_api.get('/')
def home():
return "Welcome to the SuperKart Sales Prediction API!"
# Define an endpoint to predict sales
@superkart_api.post('/v1/predict')
def predict_sales():
if preprocessor is None or model is None:
return jsonify({"error": "Model or preprocessor not loaded"}), 500
data = request.get_json()
try:
# Define the mappings exactly as in the notebook
sugar_map = {'No Sugar': 0, 'Low Sugar': 1, 'Regular': 2}
size_map = {'Small': 0, 'Medium': 1, 'High': 2}
city_type_map = {'Tier 3': 0, 'Tier 2': 1, 'Tier 1': 2}
# Extract and map the raw data
sample = {
'Product_Weight': data['Product_Weight'],
'Product_Sugar_Content': sugar_map.get(data['Product_Sugar_Content']),
'Product_Allocated_Area': data['Product_Allocated_Area'],
'Product_Type': data['Product_Type'],
'Product_MRP': data['Product_MRP'],
'Store_Size': size_map.get(data['Store_Size']),
'Store_Location_City_Type': city_type_map.get(data['Store_Location_City_Type']),
'Store_Type': data['Store_Type'],
'Store_Age': data['Store_Age']
}
# Check if any mapping failed (resulted in None)
if any(v is None for v in [sample['Product_Sugar_Content'], sample['Store_Size'], sample['Store_Location_City_Type']]):
return jsonify({"error": "Invalid value for ordinal feature (e.g., 'Store_Size', 'Product_Sugar_Content')"}), 400
except KeyError as e:
return jsonify({"error": f"Missing key in JSON payload: {e}"}), 400
except Exception as e:
return jsonify({"error": f"Error processing input: {str(e)}"}), 400
# Convert the extracted data into a 1-row DataFrame
input_data = pd.DataFrame([sample])
# --- Make a prediction ---
try:
# 1. Transform the now-mapped input data
processed_data = preprocessor.transform(input_data)
# 2. Make a prediction
prediction = model.predict(processed_data).tolist()[0]
return jsonify({'predicted_sales': round(prediction, 2)})
except Exception as e:
return jsonify({"error": f"Error during prediction: {str(e)}"}), 500
# Run the Flask app
if __name__ == '__main__':
# Bind to 7860 as required by Hugging Face
superkart_api.run(host='0.0.0.0', port=7860, debug=True)