Abhishek Kumar
Add data preprocessing and better error handling
9d6a6eb
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
import joblib
import pandas as pd
import numpy as np
from datetime import datetime
app = FastAPI()
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load the model
model = joblib.load('superkart_sales_model.joblib')
def preprocess_data(df):
# Calculate Price_Weight_Ratio
df['Price_Weight_Ratio'] = df['Product_MRP'] / df['Product_Weight']
# Calculate Store_Age
current_year = datetime.now().year
df['Store_Age'] = current_year - df['Store_Establishment_Year']
# Calculate Product_Year (assuming it's the same as Store_Establishment_Year for this example)
df['Product_Year'] = df['Store_Establishment_Year']
return df
@app.get("/")
async def root():
return {"message": "SuperKart Sales Prediction API"}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
try:
# Read the uploaded CSV file
df = pd.read_csv(file.file)
# Preprocess the data
df = preprocess_data(df)
# Make predictions
predictions = model.predict(df)
return {"predictions": predictions.tolist()}
except Exception as e:
return {"error": str(e)}, 500
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)