Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -6,6 +6,17 @@ from flask import Flask, request, jsonify
|
|
| 6 |
from recommender import recommend_products
|
| 7 |
from flask_cors import CORS
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
# --- Initialize Flask App and CORS ---
|
| 10 |
|
| 11 |
app = Flask(__name__)
|
|
@@ -13,28 +24,88 @@ CORS(app, resources={r"/api/*": {"origins": "*"}})
|
|
| 13 |
|
| 14 |
@app.route('/recommend/<int:user_id>', methods=['GET'])
|
| 15 |
def get_recommendations(user_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
try:
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
"user_id": user_id,
|
| 20 |
-
"recommendations": recommendations
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
except Exception as e:
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
# -----------------------------------------------------------------------------
|
| 27 |
-
#
|
| 28 |
# -----------------------------------------------------------------------------
|
| 29 |
|
| 30 |
if __name__ == '__main__':
|
| 31 |
port = int(os.environ.get("PORT", 7860))
|
| 32 |
debug_mode = os.environ.get("FLASK_DEBUG", "False").lower() == "true"
|
| 33 |
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
if not debug_mode:
|
|
|
|
| 36 |
from waitress import serve
|
| 37 |
serve(app, host="0.0.0.0", port=port)
|
| 38 |
else:
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 6 |
from recommender import recommend_products
|
| 7 |
from flask_cors import CORS
|
| 8 |
|
| 9 |
+
# --- Configure Logging ---
|
| 10 |
+
logging.basicConfig(
|
| 11 |
+
level=logging.INFO,
|
| 12 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 13 |
+
handlers=[
|
| 14 |
+
logging.FileHandler('app.log'),
|
| 15 |
+
logging.StreamHandler()
|
| 16 |
+
]
|
| 17 |
+
)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
# --- Initialize Flask App and CORS ---
|
| 21 |
|
| 22 |
app = Flask(__name__)
|
|
|
|
| 24 |
|
| 25 |
@app.route('/recommend/<int:user_id>', methods=['GET'])
|
| 26 |
def get_recommendations(user_id):
|
| 27 |
+
logger.info(f"=== RECOMMENDATION REQUEST START ===")
|
| 28 |
+
logger.info(f"Input - User ID: {user_id}")
|
| 29 |
+
logger.info(f"Request method: {request.method}")
|
| 30 |
+
logger.info(f"Request headers: {dict(request.headers)}")
|
| 31 |
+
logger.info(f"Request args: {dict(request.args)}")
|
| 32 |
+
|
| 33 |
try:
|
| 34 |
+
# Get optional parameters
|
| 35 |
+
top_n = request.args.get('top_n', default=5, type=int)
|
| 36 |
+
logger.info(f"Parameters - top_n: {top_n}")
|
| 37 |
+
|
| 38 |
+
logger.info("Calling recommend_products function...")
|
| 39 |
+
recommendations = recommend_products(user_id, top_n)
|
| 40 |
+
|
| 41 |
+
response_data = {
|
| 42 |
"user_id": user_id,
|
| 43 |
+
"recommendations": recommendations,
|
| 44 |
+
"total_recommendations": len(recommendations),
|
| 45 |
+
"timestamp": datetime.now().isoformat()
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
logger.info(f"Success - Generated {len(recommendations)} recommendations for user {user_id}")
|
| 49 |
+
logger.info(f"Output - Response data keys: {list(response_data.keys())}")
|
| 50 |
+
logger.info(f"Output - Recommendation IDs: {[r.get('id') for r in recommendations if isinstance(r, dict)]}")
|
| 51 |
+
logger.info(f"=== RECOMMENDATION REQUEST END ===")
|
| 52 |
+
|
| 53 |
+
return jsonify(response_data)
|
| 54 |
+
|
| 55 |
except Exception as e:
|
| 56 |
+
logger.error(f"=== RECOMMENDATION REQUEST FAILED ===")
|
| 57 |
+
logger.error(f"Error type: {type(e).__name__}")
|
| 58 |
+
logger.error(f"Error message: {str(e)}")
|
| 59 |
+
logger.exception("Full traceback:")
|
| 60 |
+
|
| 61 |
+
error_response = {
|
| 62 |
+
"error": str(e),
|
| 63 |
+
"user_id": user_id,
|
| 64 |
+
"timestamp": datetime.now().isoformat()
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
logger.error(f"Returning error response: {error_response}")
|
| 68 |
+
return jsonify(error_response), 500
|
| 69 |
+
|
| 70 |
+
@app.route('/health', methods=['GET'])
|
| 71 |
+
def health_check():
|
| 72 |
+
logger.info("=== HEALTH CHECK REQUEST ===")
|
| 73 |
+
response = {
|
| 74 |
+
"status": "healthy",
|
| 75 |
+
"timestamp": datetime.now().isoformat(),
|
| 76 |
+
"service": "recommendation-api"
|
| 77 |
+
}
|
| 78 |
+
logger.info(f"Health check response: {response}")
|
| 79 |
+
return jsonify(response)
|
| 80 |
+
|
| 81 |
+
@app.errorhandler(404)
|
| 82 |
+
def not_found(error):
|
| 83 |
+
logger.warning(f"404 Error - Path: {request.path}, Method: {request.method}")
|
| 84 |
+
return jsonify({"error": "Endpoint not found"}), 404
|
| 85 |
+
|
| 86 |
+
@app.errorhandler(500)
|
| 87 |
+
def internal_error(error):
|
| 88 |
+
logger.error(f"500 Error - Path: {request.path}, Method: {request.method}")
|
| 89 |
+
logger.exception("Internal server error:")
|
| 90 |
+
return jsonify({"error": "Internal server error"}), 500
|
| 91 |
|
| 92 |
# -----------------------------------------------------------------------------
|
| 93 |
+
# SERVER EXECUTION
|
| 94 |
# -----------------------------------------------------------------------------
|
| 95 |
|
| 96 |
if __name__ == '__main__':
|
| 97 |
port = int(os.environ.get("PORT", 7860))
|
| 98 |
debug_mode = os.environ.get("FLASK_DEBUG", "False").lower() == "true"
|
| 99 |
|
| 100 |
+
logger.info(f"=== STARTING RECOMMENDATION SERVER ===")
|
| 101 |
+
logger.info(f"Debug mode: {debug_mode}")
|
| 102 |
+
logger.info(f"Port: {port}")
|
| 103 |
+
logger.info(f"Environment variables: PORT={os.environ.get('PORT')}, FLASK_DEBUG={os.environ.get('FLASK_DEBUG')}")
|
| 104 |
+
|
| 105 |
if not debug_mode:
|
| 106 |
+
logger.info("Using Waitress server for production")
|
| 107 |
from waitress import serve
|
| 108 |
serve(app, host="0.0.0.0", port=port)
|
| 109 |
else:
|
| 110 |
+
logger.info("Using Flask development server")
|
| 111 |
+
app.run(debug=True, host="0.0.0.0", port=port)
|