File size: 4,086 Bytes
1f8582e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from flask import Flask, request, jsonify
import os
import requests
from student_recommendation_system import StudentRecommendationSystem, setup_json_directory

app = Flask(__name__)
json_dir = setup_json_directory()
recommendation_system = StudentRecommendationSystem(json_dir)

FORWARD_URL = "http://54.242.19.19:3000/api/report/send-report/"
GRADES_API_BASE_URL = "http://54.242.19.19:3000/api/grades/report/"

@app.route('/recommend/<int:student_id>', methods=['POST'])
def recommend(student_id):
    try:
        grades_api_url = f"{GRADES_API_BASE_URL}{student_id}"     
        try:
            grades_response = requests.get(grades_api_url, timeout=10)
            grades_response.raise_for_status() 
            grades_data_raw = grades_response.json()
        except requests.exceptions.RequestException as e:
            return jsonify({"error": f"Failed to fetch grades data: {str(e)}"}), 500
        except ValueError as e:
            return jsonify({"error": "Invalid JSON response from grades API"}), 500
        if "grades_data" not in grades_data_raw:
            return jsonify({"error": "No 'grades_data' found in external API response"}), 400
        email = grades_data_raw.get("email")
        if not email:
            return jsonify({"error": "No 'email' found in external API response"}), 400
        try:
            grades_data = {subject: float(score) for subject, score in grades_data_raw["grades_data"].items()}
        except (ValueError, TypeError) as e:
            return jsonify({"error": f"Invalid grades data format: {str(e)}"}), 400
        results = recommendation_system.process_student_data(grades_data=grades_data)
        strengths = results["strengths"]
        top_recs = results["top_recommendations"]
        clean_recs = [
            {k: v for k, v in rec.items() if k not in ("raw_score", "refined_score")}
            for rec in top_recs
        ]
        response_payload = {
            "email": email,
            "studentName": "Ahmed Hassan",
            "academic_strengths": strengths,
            "top_recommendations": clean_recs
        }
        model_path = os.path.join(json_dir, "ai_model.pkl")
        recommendation_system.save_ai_model(model_path)
        try:
            requests.post(FORWARD_URL, json=response_payload, timeout=10)
        except requests.exceptions.RequestException as e:
            print(f"Warning: Failed to forward data to report API: {str(e)}")
        return jsonify(response_payload), 200
    except Exception as e:
        return jsonify({"error": f"Internal server error: {str(e)}"}), 500


@app.route('/recommend', methods=['POST'])
def recommend_post():
    data = request.get_json(silent=True)
    if not data or "grades_data" not in data:
        return jsonify({"error": "No 'grades_data' provided in JSON payload."}), 400

    try:
        grades_data = {subject: float(score) for subject, score in data["grades_data"].items()}
        results = recommendation_system.process_student_data(grades_data=grades_data)
        strengths = results["strengths"]
        top_recs = results["top_recommendations"]
        clean_recs = [
            {k: v for k, v in rec.items() if k not in ("raw_score", "refined_score")}
            for rec in top_recs
        ]
        response_payload = {
            "academic_strengths": strengths,
            "top_recommendations": clean_recs
        }
        model_path = os.path.join(json_dir, "ai_model.pkl")
        recommendation_system.save_ai_model(model_path)
        
        try:
            requests.post(FORWARD_URL, json=response_payload, timeout=10)
        except requests.exceptions.RequestException as e:
            print(f"Warning: Failed to forward data to report API: {str(e)}")
            
        return jsonify(response_payload), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    port = int(os.environ.get("PORT", 7860))
    app.run(host="0.0.0.0", port=port, debug=False)