Spaces:
Sleeping
Sleeping
| 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 | |
| def index(): | |
| return render_template('index.html') | |
| 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() | |
| # HF Spaces uses port 7860 | |
| app.run(host='0.0.0.0', port=7860, debug=True) | |