File size: 13,429 Bytes
1b8f908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e8b1b4
1b8f908
 
 
 
6e8b1b4
1b8f908
 
 
 
6e8b1b4
a4582ac
6e8b1b4
a4582ac
6e8b1b4
a4582ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e8b1b4
a4582ac
6e8b1b4
68d297c
a4582ac
6e8b1b4
 
1b8f908
 
 
 
 
6e8b1b4
1b8f908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e8b1b4
1b8f908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20c1719
1b8f908
 
 
 
 
 
 
 
 
c13035f
 
 
 
 
 
 
 
 
 
 
1b8f908
 
 
 
 
d823b02
 
 
1b8f908
d823b02
1b8f908
 
 
 
 
 
76ae572
1b8f908
 
 
 
 
 
 
 
 
 
 
 
 
76ae572
1b8f908
 
 
 
d4a281c
 
 
 
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
from flask import Blueprint, request, jsonify
import requests
import os
from dotenv import load_dotenv
from utils.jwt_helper import decode_jwt
from models.history import History

load_dotenv()

recommend_bp = Blueprint('recommend', __name__)

RECOMMENDER_ENDPOINTS = {
    "movie": os.getenv("MOVIE_RECOMMENDER_URL"),
    "book": os.getenv("BOOK_RECOMMENDER_URL"),
    "tv": os.getenv("TV_RECOMMENDER_URL")
}

RESPONSE_KEYS = {
    "movie": "movies",
    "book": "books",
    "tv": "shows"
}

@recommend_bp.route('/recommend/tvshowrec', methods=['POST'])
def recommend_tv():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "No data provided"}), 400
        rec_type = data.get('type')
        genre = data.get('genre')
        top_k = data.get('top_k', 10)
        if not rec_type or not genre:
            return jsonify({"error": "Missing 'type' or 'genre'"}), 400
        if rec_type not in RECOMMENDER_ENDPOINTS or not RECOMMENDER_ENDPOINTS[rec_type]:
            return jsonify({"error": "Invalid or missing recommender URL for type."}), 400
        # JWT Authentication
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return jsonify({"error": "Missing or invalid Authorization header"}), 401
        token = auth_header.split(" ")[1]
        try:
            user_data = decode_jwt(token)
            user_id = user_data.get("user_id")
        except Exception as e:
            return jsonify({"error": "Invalid or expired token"}), 401
        # Process genres
        genres_list = [g.strip() for g in genre.split(",")] if isinstance(genre, str) else genre
        # Call microservice
        try:
            recommender_url = RECOMMENDER_ENDPOINTS[rec_type]
            response = requests.post(
                recommender_url,
                json={"genre": genre},  # Changed from "genres": genres_list to "genre": genre
                timeout=10
            )
            if not response.ok:
                return jsonify({
                    "error": f"{rec_type} service error",
                    "details": response.text,
                    "status_code": response.status_code
                }), 500
            result = response.json()
            
            # Handle TV microservice's specific response format
            if isinstance(result, list):
                # Direct list response
                raw_items = result
            elif "recommendations" in result:
                # TV microservice format: {"genre": "Tragedy", "recommendations": [...]}
                recommendations = result.get("recommendations", [])
                # Convert string recommendations to objects
                raw_items = []
                for rec in recommendations:
                    if isinstance(rec, str):
                        # Convert string to object format
                        raw_items.append({
                            "name": rec,
                            "title": rec,
                            "description": "",
                            "genre": [result.get("genre", "")],
                            "rating": None
                        })
                    else:
                        # Already an object
                        raw_items.append(rec)
            else:
                # Standard format with status
                if result.get("status") != "success":
                    error_msg = result.get("message") or result.get("error") or "Unknown error"
                    return jsonify({"error": error_msg}), 500
                raw_items = result.get(RESPONSE_KEYS.get(rec_type, "items"), [])
            
            # Normalize response format
            normalized = []
            for item in raw_items:
                normalized.append({
                    "type": rec_type,
                    "name": item.get("name") or item.get("title"),
                    "creator": item.get("director") or item.get("author") or item.get("creator"),
                    "description": item.get("description", ""),
                    "genre": item.get("genre", []),
                    "rating": item.get("rating"),
                    "year": item.get("year"),
                    "image_url": item.get("image_url")
                })
            # Save to history
            try:
                history = History(
                    user_id=user_id,
                    recommendation_type=rec_type,
                    genre=genres_list,
                    items=normalized,
                    query_params={"top_k": top_k}
                )
                history.save()
                print(f"Saved recommendation history for user {user_id}")
            except Exception as e:
                print(f"Failed to save history: {e}")
                # Don't fail the request if history saving fails
            return jsonify({
                "status": "success",
                "recommendations": normalized,
                "count": len(normalized),
                "type": rec_type,
                "genres": genres_list
            }), 200
        except requests.exceptions.Timeout:
            return jsonify({"error": f"{rec_type} service timeout"}), 504
        except requests.exceptions.RequestException as e:
            return jsonify({"error": f"Failed to connect to {rec_type} service", "details": str(e)}), 503
    except Exception as e:
        print(f"Recommend error: {e}")
        return jsonify({"error": "Internal server error"}), 500
        

@recommend_bp.route('/recommend/movies', methods=['POST'])
def recommend_movie():
    try:
        data = request.get_json()

        if not data:
            return jsonify({"error": "No data provided"}), 400

        rec_type = data.get('type')
        genre = data.get('genre')
        top_k = data.get('top_k', 10)

        if not rec_type or not genre:
            return jsonify({"error": "Missing 'type' or 'genre'"}), 400

        if rec_type not in RECOMMENDER_ENDPOINTS or not RECOMMENDER_ENDPOINTS[rec_type]:
            return jsonify({"error": "Invalid or missing recommender URL for type."}), 400

        # JWT Authentication
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return jsonify({"error": "Missing or invalid Authorization header"}), 401

        token = auth_header.split(" ")[1]
        try:
            user_data = decode_jwt(token)
            user_id = user_data.get("user_id")
        except Exception as e:
            return jsonify({"error": "Invalid or expired token"}), 401

        # Process genres
        genres_list = [g.strip() for g in genre.split(",")] if isinstance(genre, str) else genre

        # Call microservice
        try:
            recommender_url = RECOMMENDER_ENDPOINTS[rec_type]
            response = requests.post(
                recommender_url,
                json={"genres": genres_list, "top_k": top_k},
                timeout=10
            )

            if not response.ok:
                return jsonify({
                    "error": f"{rec_type} service error", 
                    "details": response.text,
                    "status_code": response.status_code
                }), 500

            result = response.json()
            if result.get("status") != "success":
                return jsonify({"error": result.get("message", "Unknown error")}), 500

            raw_items = result.get(RESPONSE_KEYS.get(rec_type, "items"), [])

            # Normalize response format
            normalized = []
            for item in raw_items:
                normalized.append({
                    "type": rec_type,
                    "name": item.get("name") or item.get("title"),  
                    "creator": item.get("director") or item.get("author") or item.get("creator"),
                    "description": item.get("description", ""),
                    "genre": item.get("genre", []),
                    "rating": item.get("rating")
                })

            # Save to history
            try:
                history = History(
                    user_id=user_id,
                    recommendation_type=rec_type,
                    genre=genres_list,
                    items=normalized,
                    query_params={"top_k": top_k}
                )
                history.save()
                print(f"Saved recommendation history for user {user_id}")
            except Exception as e:
                print(f"Failed to save history: {e}")
                # Don't fail the request if history saving fails

            return jsonify({
                "status": "success",
                "recommendations": normalized,
                "count": len(normalized),
                "type": rec_type,
                "genres": genres_list
            }), 200

        except requests.exceptions.Timeout:
            return jsonify({"error": f"{rec_type} service timeout"}), 504
        except requests.exceptions.RequestException as e:
            return jsonify({"error": f"Failed to connect to {rec_type} service", "details": str(e)}), 503

    except Exception as e:
        print(f"Recommend error: {e}")
        return jsonify({"error": "Internal server error"}), 500


@recommend_bp.route('/recommend/book', methods=['POST'])
def recommend_book():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "No data provided"}), 400
        rec_type = data.get('type')
        genre = data.get('genre')
        top_k = data.get('top_k', 10)
        if not rec_type or not genre:
            return jsonify({"error": "Missing 'type' or 'genre'"}), 400
        if rec_type not in RECOMMENDER_ENDPOINTS or not RECOMMENDER_ENDPOINTS[rec_type]:
            return jsonify({"error": "Invalid or missing recommender URL for type."}), 400
        # JWT Authentication
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return jsonify({"error": "Missing or invalid Authorization header"}), 401
        token = auth_header.split(" ")[1]
        try:
            user_data = decode_jwt(token)
            user_id = user_data.get("user_id")
        except Exception as e:
            return jsonify({"error": "Invalid or expired token"}), 401
        # Call microservice
        try:
            recommender_url = RECOMMENDER_ENDPOINTS[rec_type]
            response = requests.post(
                recommender_url,
                json={"genre": genre},  # Single string as expected
                timeout=10
            )
            if not response.ok:
                return jsonify({
                    "error": f"{rec_type} service error", 
                    "details": response.text,
                    "status_code": response.status_code
                }), 500
            result = response.json()
            
            # Handle different response formats
            if isinstance(result, list):
                # Microservice returns a direct list of books
                raw_items = result
            else:
                # Microservice returns structured response with status
                if result.get("status") != "success":
                    return jsonify({"error": result.get("message", "Unknown error")}), 500
                raw_items = result.get(RESPONSE_KEYS.get(rec_type, "items"), [])
            
            # Normalize response format
            normalized = []
            for item in raw_items:
                normalized.append({
                    "type": rec_type,
                    "name": item.get("name") or item.get("Title"),  
                    "creator": item.get("director") or item.get("Author") or item.get("creator"),
                    # "description": item.get("description", ""),
                    "genre": item.get("genre", []),
                    "rating": item.get("avg_rating")
                })
            # Save to history
            try:
                history = History(
                    user_id=user_id,
                    recommendation_type=rec_type,
                    genre=[genre],  # Fixed: wrap single genre in list for History model
                    items=normalized,
                    query_params={"top_k": top_k}
                )
                history.save()
                print(f"Saved recommendation history for user {user_id}")
            except Exception as e:
                print(f"Failed to save history: {e}")
                # Don't fail the request if history saving fails
            return jsonify({
                "status": "success",
                "recommendations": normalized,
                "count": len(normalized),
                "type": rec_type,
                "genres": [genre]  #Fixed: wrap single genre in list for consistency
            }), 200
        except requests.exceptions.Timeout:
            return jsonify({"error": f"{rec_type} service timeout"}), 504
        except requests.exceptions.RequestException as e:
            return jsonify({"error": f"Failed to connect to {rec_type} service", "details": str(e)}), 503
    except Exception as e:
        print(f"Recommend error: {e}")
        return jsonify({"error": "Internal server error"}), 500