diff --git a/app/api/api_recommendation.py b/app/api/api_recommendation.py index c533709..93fb251 100644 --- a/app/api/api_recommendation.py +++ b/app/api/api_recommendation.py @@ -31,6 +31,15 @@ async def startup_event(): scheduler.start() logger.info("定时任务已启动") +def get_random_recommendations(category: str, num: int) -> List[str]: + """全品类随机推荐""" + all_iids = list(matrix_data["iid_to_sketch"].keys()) + # 优先从当前品类选择 + category_iids = matrix_data["category_to_iids"].get(category, all_iids) + # 确保不超出实际数量 + sample_size = min(num, len(category_iids)) + sampled = np.random.choice(category_iids, size=sample_size, replace=False) + return [matrix_data["iid_to_sketch"][iid] for iid in sampled] @router.get("/recommend/{user_id}/{category}/{num_recommendations}", response_model=List[str]) async def get_recommendations(user_id: int, category: str, num_recommendations: int = 10): @@ -46,6 +55,14 @@ async def get_recommendations(user_id: int, category: str, num_recommendations: try: start_time = time.time() cache_key = (user_id, category) + # === 新增:用户存在性检查 === + user_exists_inter = user_id in matrix_data["user_index_interaction"] + user_exists_feat = user_id in matrix_data["user_index_feature"] + + # 任一矩阵不存在用户则返回随机推荐 + if not (user_exists_inter and user_exists_feat): + logger.info(f"用户 {user_id} 数据不完整,触发随机推荐") + return get_random_recommendations(category, num_recommendations) # 检查缓存 if cache_key in matrix_data["cached_scores"]: @@ -100,7 +117,7 @@ async def get_recommendations(user_id: int, category: str, num_recommendations: exps = np.exp(scale) return exps / np.sum(exps) - probs = calibrated_softmax(scores, 0.07) + probs = calibrated_softmax(scores, 0.09) chosen_indices = np.random.choice( len(valid_sketch_idxs), @@ -115,4 +132,4 @@ async def get_recommendations(user_id: int, category: str, num_recommendations: except Exception as e: logger.error(f"推荐失败: {str(e)}", exc_info=True) - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=str(e)) \ No newline at end of file