superkart-api1 / app.py
Vbhadiar's picture
Upload folder using huggingface_hub
5404586 verified
import os
import joblib
import pandas as pd
import numpy as np
from pathlib import Path
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# Define the model path
MODEL_PATH = Path("backend_files/final_model.joblib")
# Load the model once at startup
try:
if not MODEL_PATH.is_file():
raise FileNotFoundError(f"Model file not found at: {MODEL_PATH.resolve()}")
model = joblib.load(MODEL_PATH)
print("Model loaded successfully.")
except Exception as e:
print(f"Error loading model: {e}")
model = None
@app.get("/")
def health():
return {"status": "ok", "model_loaded": model is not None}, 200
@app.post("/predict")
def predict():
if model is None:
return jsonify({"error": "Model not loaded. Check startup logs."}), 500
try:
# Get data from POST request
data = request.get_json(force=True)
data_df = pd.DataFrame([data])
# Make prediction (in log scale) and inverse transform
prediction_log = model.predict(data_df)
prediction = np.expm1(prediction_log)
return jsonify({'prediction': prediction.tolist()})
except Exception as e:
return jsonify({'error': str(e)}), 400
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)