File size: 1,308 Bytes
5404586
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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)