File size: 1,769 Bytes
5575a8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
from flask import Flask, request, jsonify, render_template
import tensorflow as tf
import numpy as np
import joblib
import os

app = Flask(__name__)

# Load model and scalers globally for efficiency
MODEL_PATH = 'student_marks_rnn_model.h5'
SCALER_X_PATH = 'scaler_X.pkl'
SCALER_Y_PATH = 'scaler_y.pkl'

model = None
scaler_X = None
scaler_y = None

def load_resources():
    global model, scaler_X, scaler_y
    if os.path.exists(MODEL_PATH) and os.path.exists(SCALER_X_PATH) and os.path.exists(SCALER_Y_PATH):
        model = tf.keras.models.load_model(MODEL_PATH)
        scaler_X = joblib.load(SCALER_X_PATH)
        scaler_y = joblib.load(SCALER_Y_PATH)
        return True
    return False

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    if model is None:
        if not load_resources():
            return jsonify({'error': 'Model or scalers not found. Run training first.'}), 500

    try:
        data = request.get_json()
        num_courses = float(data['num_courses'])
        time_study = float(data['time_study'])

        # Preprocess
        input_data = np.array([[num_courses, time_study]])
        input_scaled = scaler_X.transform(input_data)
        input_reshaped = input_scaled.reshape((1, 1, 2))

        # Predict
        prediction_scaled = model.predict(input_reshaped)
        prediction = scaler_y.inverse_transform(prediction_scaled)
        
        result = float(prediction[0][0])
        return jsonify({'marks': round(result, 2)})

    except Exception as e:
        return jsonify({'error': str(e)}), 400

if __name__ == '__main__':
    load_resources()
    app.run(debug=True, port=5000)