Spaces:
Runtime error
Runtime error
Update routes/recommend.py
Browse files- routes/recommend.py +15 -22
routes/recommend.py
CHANGED
|
@@ -25,63 +25,59 @@ RESPONSE_KEYS = {
|
|
| 25 |
def recommend_tv():
|
| 26 |
try:
|
| 27 |
data = request.get_json()
|
| 28 |
-
|
| 29 |
if not data:
|
| 30 |
return jsonify({"error": "No data provided"}), 400
|
| 31 |
-
|
| 32 |
rec_type = data.get('type')
|
| 33 |
genre = data.get('genre')
|
| 34 |
top_k = data.get('top_k', 10)
|
| 35 |
-
|
| 36 |
if not rec_type or not genre:
|
| 37 |
return jsonify({"error": "Missing 'type' or 'genre'"}), 400
|
| 38 |
-
|
| 39 |
if rec_type not in RECOMMENDER_ENDPOINTS or not RECOMMENDER_ENDPOINTS[rec_type]:
|
| 40 |
return jsonify({"error": "Invalid or missing recommender URL for type."}), 400
|
| 41 |
-
|
| 42 |
# JWT Authentication
|
| 43 |
auth_header = request.headers.get('Authorization')
|
| 44 |
if not auth_header or not auth_header.startswith('Bearer '):
|
| 45 |
return jsonify({"error": "Missing or invalid Authorization header"}), 401
|
| 46 |
-
|
| 47 |
token = auth_header.split(" ")[1]
|
| 48 |
try:
|
| 49 |
user_data = decode_jwt(token)
|
| 50 |
user_id = user_data.get("user_id")
|
| 51 |
except Exception as e:
|
| 52 |
return jsonify({"error": "Invalid or expired token"}), 401
|
| 53 |
-
|
| 54 |
# Process genres
|
| 55 |
genres_list = [g.strip() for g in genre.split(",")] if isinstance(genre, str) else genre
|
| 56 |
-
|
| 57 |
# Call microservice
|
| 58 |
try:
|
| 59 |
recommender_url = RECOMMENDER_ENDPOINTS[rec_type]
|
| 60 |
response = requests.post(
|
| 61 |
recommender_url,
|
| 62 |
-
json={"genres": genres_list
|
| 63 |
timeout=10
|
| 64 |
)
|
| 65 |
-
|
| 66 |
if not response.ok:
|
| 67 |
return jsonify({
|
| 68 |
-
"error": f"{rec_type} service error",
|
| 69 |
"details": response.text,
|
| 70 |
"status_code": response.status_code
|
| 71 |
}), 500
|
| 72 |
-
|
| 73 |
result = response.json()
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
# Normalize response format
|
| 80 |
normalized = []
|
| 81 |
for item in raw_items:
|
| 82 |
normalized.append({
|
| 83 |
"type": rec_type,
|
| 84 |
-
"name": item.get("name") or item.get("title"),
|
| 85 |
"creator": item.get("director") or item.get("author") or item.get("creator"),
|
| 86 |
"description": item.get("description", ""),
|
| 87 |
"genre": item.get("genre", []),
|
|
@@ -89,7 +85,6 @@ def recommend_tv():
|
|
| 89 |
"year": item.get("year"),
|
| 90 |
"image_url": item.get("image_url")
|
| 91 |
})
|
| 92 |
-
|
| 93 |
# Save to history
|
| 94 |
try:
|
| 95 |
history = History(
|
|
@@ -104,7 +99,6 @@ def recommend_tv():
|
|
| 104 |
except Exception as e:
|
| 105 |
print(f"Failed to save history: {e}")
|
| 106 |
# Don't fail the request if history saving fails
|
| 107 |
-
|
| 108 |
return jsonify({
|
| 109 |
"status": "success",
|
| 110 |
"recommendations": normalized,
|
|
@@ -112,15 +106,14 @@ def recommend_tv():
|
|
| 112 |
"type": rec_type,
|
| 113 |
"genres": genres_list
|
| 114 |
}), 200
|
| 115 |
-
|
| 116 |
except requests.exceptions.Timeout:
|
| 117 |
return jsonify({"error": f"{rec_type} service timeout"}), 504
|
| 118 |
except requests.exceptions.RequestException as e:
|
| 119 |
return jsonify({"error": f"Failed to connect to {rec_type} service", "details": str(e)}), 503
|
| 120 |
-
|
| 121 |
except Exception as e:
|
| 122 |
print(f"Recommend error: {e}")
|
| 123 |
return jsonify({"error": "Internal server error"}), 500
|
|
|
|
| 124 |
|
| 125 |
@recommend_bp.route('/recommend/movies', methods=['POST'])
|
| 126 |
def recommend_movie():
|
|
|
|
| 25 |
def recommend_tv():
|
| 26 |
try:
|
| 27 |
data = request.get_json()
|
|
|
|
| 28 |
if not data:
|
| 29 |
return jsonify({"error": "No data provided"}), 400
|
|
|
|
| 30 |
rec_type = data.get('type')
|
| 31 |
genre = data.get('genre')
|
| 32 |
top_k = data.get('top_k', 10)
|
|
|
|
| 33 |
if not rec_type or not genre:
|
| 34 |
return jsonify({"error": "Missing 'type' or 'genre'"}), 400
|
|
|
|
| 35 |
if rec_type not in RECOMMENDER_ENDPOINTS or not RECOMMENDER_ENDPOINTS[rec_type]:
|
| 36 |
return jsonify({"error": "Invalid or missing recommender URL for type."}), 400
|
|
|
|
| 37 |
# JWT Authentication
|
| 38 |
auth_header = request.headers.get('Authorization')
|
| 39 |
if not auth_header or not auth_header.startswith('Bearer '):
|
| 40 |
return jsonify({"error": "Missing or invalid Authorization header"}), 401
|
|
|
|
| 41 |
token = auth_header.split(" ")[1]
|
| 42 |
try:
|
| 43 |
user_data = decode_jwt(token)
|
| 44 |
user_id = user_data.get("user_id")
|
| 45 |
except Exception as e:
|
| 46 |
return jsonify({"error": "Invalid or expired token"}), 401
|
|
|
|
| 47 |
# Process genres
|
| 48 |
genres_list = [g.strip() for g in genre.split(",")] if isinstance(genre, str) else genre
|
|
|
|
| 49 |
# Call microservice
|
| 50 |
try:
|
| 51 |
recommender_url = RECOMMENDER_ENDPOINTS[rec_type]
|
| 52 |
response = requests.post(
|
| 53 |
recommender_url,
|
| 54 |
+
json={"genre": genre}, # Changed from "genres": genres_list to "genre": genre
|
| 55 |
timeout=10
|
| 56 |
)
|
|
|
|
| 57 |
if not response.ok:
|
| 58 |
return jsonify({
|
| 59 |
+
"error": f"{rec_type} service error",
|
| 60 |
"details": response.text,
|
| 61 |
"status_code": response.status_code
|
| 62 |
}), 500
|
|
|
|
| 63 |
result = response.json()
|
| 64 |
+
|
| 65 |
+
# Handle different response formats (like book route)
|
| 66 |
+
if isinstance(result, list):
|
| 67 |
+
# Microservice returns a direct list
|
| 68 |
+
raw_items = result
|
| 69 |
+
else:
|
| 70 |
+
# Microservice returns structured response with status
|
| 71 |
+
if result.get("status") != "success":
|
| 72 |
+
return jsonify({"error": result.get("message", "Unknown error")}), 500
|
| 73 |
+
raw_items = result.get(RESPONSE_KEYS.get(rec_type, "items"), [])
|
| 74 |
+
|
| 75 |
# Normalize response format
|
| 76 |
normalized = []
|
| 77 |
for item in raw_items:
|
| 78 |
normalized.append({
|
| 79 |
"type": rec_type,
|
| 80 |
+
"name": item.get("name") or item.get("title"),
|
| 81 |
"creator": item.get("director") or item.get("author") or item.get("creator"),
|
| 82 |
"description": item.get("description", ""),
|
| 83 |
"genre": item.get("genre", []),
|
|
|
|
| 85 |
"year": item.get("year"),
|
| 86 |
"image_url": item.get("image_url")
|
| 87 |
})
|
|
|
|
| 88 |
# Save to history
|
| 89 |
try:
|
| 90 |
history = History(
|
|
|
|
| 99 |
except Exception as e:
|
| 100 |
print(f"Failed to save history: {e}")
|
| 101 |
# Don't fail the request if history saving fails
|
|
|
|
| 102 |
return jsonify({
|
| 103 |
"status": "success",
|
| 104 |
"recommendations": normalized,
|
|
|
|
| 106 |
"type": rec_type,
|
| 107 |
"genres": genres_list
|
| 108 |
}), 200
|
|
|
|
| 109 |
except requests.exceptions.Timeout:
|
| 110 |
return jsonify({"error": f"{rec_type} service timeout"}), 504
|
| 111 |
except requests.exceptions.RequestException as e:
|
| 112 |
return jsonify({"error": f"Failed to connect to {rec_type} service", "details": str(e)}), 503
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
print(f"Recommend error: {e}")
|
| 115 |
return jsonify({"error": "Internal server error"}), 500
|
| 116 |
+
|
| 117 |
|
| 118 |
@recommend_bp.route('/recommend/movies', methods=['POST'])
|
| 119 |
def recommend_movie():
|