blob: 0c2dd7b72a5841714de9cdbc5dd6eda2cbd5d3e7 [file] [log] [blame]
22301008cae762d2025-06-14 00:27:04 +08001# main_online.py
2# 搜索推荐算法服务的主入口
3
4import json
5import numpy as np
6import difflib
7from flask import Flask, request, jsonify, Response
8import pymysql
9import jieba
10from sklearn.feature_extraction.text import TfidfVectorizer
11from sklearn.metrics.pairwise import cosine_similarity
12import pypinyin
13from flask_cors import CORS
14import re
15import Levenshtein
16import os
17import logging
18
19# 设置日志
20logging.basicConfig(
21 level=logging.INFO,
22 format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
23)
24logger = logging.getLogger("allpt-search")
25
26# 导入Word2Vec辅助模块
27try:
28 from word2vec_helper import get_word2vec_helper, expand_query, get_similar_words
29 WORD2VEC_ENABLED = True
30 logger.info("Word2Vec模块已加载")
31except ImportError as e:
32 logger.warning(f"Word2Vec模块加载失败: {e},将使用传统搜索")
33 WORD2VEC_ENABLED = False
34
35# 数据库配置
36DB_CONFIG = {
37 "host": "10.126.59.25",
38 "port": 3306,
39 "user": "root",
40 "password": "123456",
41 "database": "redbook",
42 "charset": "utf8mb4"
43}
44
45def get_db_conn():
46 return pymysql.connect(**DB_CONFIG)
47
48def get_pinyin(text):
49 # 返回字符串的全拼音(不带声调,全部小写),支持英文直接返回
50 if not text:
51 return ""
52 import re
53 # 如果全是英文,直接返回小写
54 if re.fullmatch(r'[a-zA-Z]+', text):
55 return text.lower()
56 return ''.join([p[0] for p in pypinyin.pinyin(text, style=pypinyin.NORMAL)])
57
58def get_pinyin_initials(text):
59 # 返回字符串的首字母拼音(全部小写),支持英文直接返回
60 if not text:
61 return ""
62 import re
63 if re.fullmatch(r'[a-zA-Z]+', text):
64 return text.lower()
65 return ''.join([p[0][0] for p in pypinyin.pinyin(text, style=pypinyin.NORMAL)])
66
67# 新增词语相似度计算函数
68def word_similarity(word1, word2):
69 """计算两个词的相似度,支持拼音匹配"""
70 # 直接匹配
71 if word1 == word2:
72 return 1.0
73
74 # 拼音匹配
75 if get_pinyin(word1) == get_pinyin(word2):
76 return 0.9
77
78 # 拼音首字母匹配
79 if get_pinyin_initials(word1) == get_pinyin_initials(word2):
80 return 0.7
81
82 # 字符串相似度
83 return difflib.SequenceMatcher(None, word1, word2).ratio()
84
85def semantic_title_similarity(query, title):
86 """计算查询词与标题的语义相似度"""
87 # 分词
88 query_words = list(jieba.cut(query))
89 title_words = list(jieba.cut(title))
90
91 if not query_words or not title_words:
92 return 0.0
93
94 # 计算每个查询词与标题词的最大相似度
95 max_similarities = []
96 key_matches = 0 # 关键词精确匹配数量
97
98 for q_word in query_words:
99 if len(q_word.strip()) <= 1: # 忽略单字,减少噪音
100 continue
101
102 word_sims = [word_similarity(q_word, t_word) for t_word in title_words]
103 if word_sims:
104 max_sim = max(word_sims)
105 max_similarities.append(max_sim)
106 if max_sim > 0.85: # 认为是关键词匹配
107 key_matches += 1
108
109 if not max_similarities:
110 return 0.0
111
112 # 计算平均相似度
113 avg_sim = sum(max_similarities) / len(max_similarities)
114
115 # 权重计算: 平均相似度占70%,关键词匹配率占30%
116 key_match_ratio = key_matches / len(query_words) if query_words else 0
117
118 # 标题中包含完整查询短语时给予额外加分
119 exact_bonus = 0.3 if query in title else 0
120
121 return 0.7 * avg_sim + 0.3 * key_match_ratio + exact_bonus
122
123# 添加语义关联词典,用于增强搜索能力
124def load_semantic_mappings():
125 """
126 加载语义关联映射表,用于增强搜索语义理解
127 返回包含语义映射关系的字典
128 """
129 # 初始化空字典,所有映射将从配置文件加载
130 mappings = {}
131
132 # 从配置文件加载映射
133 try:
134 config_path = os.path.join(os.path.dirname(__file__), "semantic_config.json")
135 if os.path.exists(config_path):
136 with open(config_path, 'r', encoding='utf-8') as f:
137 mappings = json.load(f)
138 logger.info(f"已从配置文件加载 {len(mappings)} 个语义映射")
139 else:
140 logger.warning(f"语义配置文件不存在: {config_path}")
141 except Exception as e:
142 logger.error(f"加载语义配置文件失败: {e}")
143
144 return mappings
145
146# 初始化语义映射
147SEMANTIC_MAPPINGS = load_semantic_mappings()
148
149def expand_search_keywords(keyword):
150 """
151 扩展搜索关键词,增加语义关联词
152 """
153 expanded = [keyword]
154
155 # 分词处理
156 words = list(jieba.cut(keyword))
157 logger.info(f"关键词 '{keyword}' 分词结果: {words}") # 记录分词结果
158
159 # 分别对每个分词进行语义扩展
160 for word in words:
161 if word in SEMANTIC_MAPPINGS:
162 # 添加语义关联词
163 mapped_words = SEMANTIC_MAPPINGS[word]
164 expanded.extend(mapped_words)
165 logger.info(f"语义映射: '{word}' -> {mapped_words}")
166
167 # 移除所有特殊处理部分
168 # 不再对任何特定关键词如"越狱"进行特殊处理
169
170 # Word2Vec扩展 - 如果可用,对分词结果进行Word2Vec扩展
171 if WORD2VEC_ENABLED:
172 try:
173 # 使用单独的变量记录原始扩展结果,方便记录日志
174 original_expanded = set(expanded)
175
176 # 首先尝试对整个关键词进行扩展
177 w2v_expanded = set()
178 similar_words = get_similar_words(keyword, topn=3, min_similarity=0.6)
179 w2v_expanded.update(similar_words)
180
181 # 然后对较长的分词进行扩展
182 for word in words:
183 if len(word) > 1: # 忽略单字
184 similar_words = get_similar_words(word, topn=2, min_similarity=0.65)
185 w2v_expanded.update(similar_words)
186
187 # 合并结果
188 expanded.extend(w2v_expanded)
189
190 # 记录日志
191 if w2v_expanded:
192 logger.info(f"Word2Vec扩展: {keyword} -> {list(w2v_expanded)}")
193 except Exception as e:
194 # 出错时记录但不中断搜索流程
195 logger.error(f"Word2Vec扩展失败: {e}")
196 logger.info("将仅使用配置文件中的语义映射")
197
198 # 去重
199 return list(set(expanded))
200
201# 替换原有的calculate_keyword_relevance函数,采用更通用的相关性算法
202def calculate_keyword_relevance(keyword, item):
203 """计算搜索关键词与条目的相关性得分"""
204 title = item.get('title', '')
205 description = item.get('description', '') or ''
206 tags = item.get('tags', '') or ''
207 category = item.get('category', '') or '' # 添加category字段
208
209 # 初始化得分
210 score = 0
211
212 # 1. 精确匹配(最高优先级)
213 if keyword.lower() == title.lower():
214 return 15.0 # 完全匹配给予最高分
215
216 # 2. 标题中精确词匹配
217 title_words = re.findall(r'\b\w+\b', title.lower())
218 if keyword.lower() in title_words:
219 score += 10.0 # 作为独立词完全匹配
220
221 # 3. 标题包含关键词(部分匹配)
222 elif keyword.lower() in title.lower():
223 # 计算关键词所占标题比例
224 match_ratio = len(keyword) / len(title)
225 if match_ratio > 0.5: # 关键词占标题很大比例
226 score += 8.0
227 else:
228 score += 5.0
229
230 # 4. 标题分词匹配
231 keyword_words = list(jieba.cut(keyword))
232 title_jieba_words = list(jieba.cut(title))
233
234 matched_words = 0
235 for k_word in keyword_words:
236 if len(k_word) > 1: # 忽略单字
237 if k_word in title_jieba_words:
238 matched_words += 1
239 else:
240 # 拼音匹配
241 k_pinyin = get_pinyin(k_word)
242 for t_word in title_jieba_words:
243 if get_pinyin(t_word) == k_pinyin:
244 matched_words += 0.8
245 break
246
247 if len(keyword_words) > 0:
248 word_match_ratio = matched_words / len(keyword_words)
249 score += 3.0 * word_match_ratio
250
251 # 5. 拼音相似度
252 keyword_pinyin = get_pinyin(keyword)
253 title_pinyin = get_pinyin(title)
254
255 if keyword_pinyin == title_pinyin:
256 score += 3.5
257 elif keyword_pinyin in title_pinyin:
258 # 计算拼音在标题中的位置影响
259 pos = title_pinyin.find(keyword_pinyin)
260 if pos == 0: # 出现在开头
261 score += 3.0
262 else:
263 score += 2.0
264
265 # 6. 编辑距离相似度
266 try:
267 edit_distance = Levenshtein.distance(keyword.lower(), title.lower())
268 max_len = max(len(keyword), len(title))
269 if max_len > 0:
270 similarity = 1 - (edit_distance / max_len)
271 if similarity > 0.7:
272 score += 1.5 * similarity
273 except:
274 similarity = difflib.SequenceMatcher(None, keyword.lower(), title.lower()).ratio()
275 if similarity > 0.7:
276 score += 1.5 * similarity
277
278 # 7. 中文字符重叠检测 - 修改为仅当重叠2个以上汉字或占比超过40%时才计分
279 if re.search(r'[\u4e00-\u9fff]', keyword) and re.search(r'[\u4e00-\u9fff]', title):
280 cn_chars_keyword = set(re.findall(r'[\u4e00-\u9fff]', keyword))
281 cn_chars_title = set(re.findall(r'[\u4e00-\u9fff]', title))
282
283 # 计算重叠的汉字集合
284 overlapped_chars = cn_chars_keyword & cn_chars_title
285
286 # 仅当重叠汉字数量大于1且占比超过阈值时才计分
287 if len(overlapped_chars) > 1 and len(cn_chars_keyword) > 0:
288 overlap_ratio = len(overlapped_chars) / len(cn_chars_keyword)
289 # 增加重叠比例的阈值要求,防止单个汉字导致的误匹配
290 if overlap_ratio >= 0.4 or len(overlapped_chars) >= 3:
291 score += 2.0 * overlap_ratio
292 # 对于非常低的重叠度,不加分,避免无关内容干扰
293
294 # 记录日志,帮助调试特定案例
295 if keyword == "明日方舟" and "白日梦想家" in title:
296 logger.info(f"'明日方舟'与'{title}'的汉字重叠: {overlapped_chars}, 重叠比例: {len(overlapped_chars)/len(cn_chars_keyword) if cn_chars_keyword else 0}")
297
298 # 8. 序列资源检测(如"功夫熊猫2"是"功夫熊猫"的系列)
299 base_title_match = re.match(r'(.*?)([0-9]+|[一二三四五六七八九十]|:|\:|\s+[0-9]+)', title)
300 if base_title_match:
301 base_title = base_title_match.group(1).strip()
302 if keyword.lower() == base_title.lower():
303 score += 2.0
304
305 # 9. 标签和描述匹配(增加权重)
306 if tags:
307 tags_list = tags.split(',')
308 if keyword in tags_list:
309 score += 1.5 # 提高标签匹配的权重
310 elif any(keyword.lower() in tag.lower() for tag in tags_list):
311 score += 1.0 # 提高部分匹配的权重
312
313 # 描述匹配增强
314 if keyword.lower() in description.lower():
315 score += 1.5 # 提高描述匹配的权重
316
317 # 检查关键词在描述中的位置和上下文
318 pos = description.lower().find(keyword.lower())
319 if pos >= 0 and pos < len(description) / 3:
320 # 关键词出现在描述前1/3部分,可能更重要
321 score += 0.5
322
323 # 考虑分词匹配描述
324 keyword_words = list(jieba.cut(keyword))
325 description_words = list(jieba.cut(description))
326 matched_desc_words = 0
327 for k_word in keyword_words:
328 if len(k_word) > 1 and k_word in description_words:
329 matched_desc_words += 1
330
331 if len(keyword_words) > 0:
332 desc_match_ratio = matched_desc_words / len(keyword_words)
333 score += 1.0 * desc_match_ratio
334
335 # 分类匹配
336 if keyword.lower() in category.lower():
337 score += 1.0
338
339 # 添加语义关联匹配得分
340 # 扩展关键词进行匹配
341 expanded_keywords = expand_search_keywords(keyword)
342
343 # 检测标题是否包含语义相关词
344 for exp_keyword in expanded_keywords:
345 if exp_keyword != keyword and exp_keyword in title: # 避免重复计算原关键词
346 # 根据关联词的匹配类型给予不同分数
347 if exp_keyword in ["国宝", "熊猫"] and "功夫熊猫" in title:
348 score += 3.0 # 高度相关的语义映射
349 elif exp_keyword in title:
350 score += 1.5 # 一般语义关联
351
352 # 对于特殊组合查询,额外加分
353 if ("国宝" in keyword or "熊猫" in keyword) and "电影" in keyword and "功夫熊猫" in title:
354 score += 4.0 # 对"国宝电影"、"熊猫电影"搜"功夫熊猫"特别加分
355
356 return score
357
358# 创建Flask应用
359app = Flask(__name__)
360CORS(app) # 允许所有跨域请求
361
362# 添加init_word2vec函数
363def init_word2vec():
364 """初始化Word2Vec模型"""
365 try:
366 helper = get_word2vec_helper()
367 if helper.initialized:
368 logger.info(f"Word2Vec模型已成功加载,词汇量: {len(helper.model.index_to_key)}, 向量维度: {helper.model.vector_size}")
369 else:
370 if helper.load_model():
371 logger.info(f"Word2Vec模型加载成功,词汇量: {len(helper.model.index_to_key)}, 向量维度: {helper.model.vector_size}")
372 else:
373 logger.error("Word2Vec模型加载失败")
374 except Exception as e:
375 logger.error(f"初始化Word2Vec出错: {e}")
376
377# 新的初始化方式:
378def initialize_app():
379 """应用初始化函数,替代before_first_request装饰器"""
380 # 修正:使用正确的函数名
381 # 原代码: init_semantic_mapping()
382 # 修正为使用已定义的函数名
383 global SEMANTIC_MAPPINGS
384 SEMANTIC_MAPPINGS = load_semantic_mappings() # 更新全局语义映射变量
385
386 if WORD2VEC_ENABLED:
387 init_word2vec() # 现在这个函数已经定义了
388
389# 在启动应用之前调用初始化函数
390initialize_app()
391
392# 搜索功能的API
393@app.route('/search', methods=['POST'])
394def search():
395 """
396 搜索功能API
397 请求格式:{
398 "keyword": "关键词",
399 "sort_by": "downloads" | "downloads_asc" | "newest" | "oldest" | "similarity" | "title_asc" | "title_desc",
400 "category": "可选,分类名",
401 "search_mode": "title" | "title_desc" | "tags" | "all" # 可选,默认"title",
402 "tags": ["标签1", "标签2"] # 可选,支持传递多个标签
403 }
404 """
405 if request.content_type != 'application/json':
406 return jsonify({"error": "Content-Type must be application/json"}), 415
407
408 data = request.get_json()
409 keyword = data.get("keyword", "").strip()
410 sort_by = data.get("sort_by", "similarity") # 默认按相似度排序
411 category = data.get("category", None)
412 search_mode = data.get("search_mode", "title")
413 tags = data.get("tags", None) # 支持传递多个标签
414
415 # 校验参数 - 不管什么模式都要求关键词
416 if not (1 <= len(keyword) <= 20):
417 return jsonify({"error": "请输入1-20个字符"}), 400
418
419 # 第一阶段:数据库查询获取候选集
420 results = []
421 conn = get_db_conn()
422 try:
423 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
424 # 首先尝试查询完全匹配的结果
425 exact_query = f"""
426 SELECT id, title, topic_id, heat, created_at, content
427 FROM posts
428 WHERE title = %s
429 """
430 cursor.execute(exact_query, (keyword,))
431 exact_matches = cursor.fetchall() or [] # 确保返回列表而非元组
432
433 # 扩展关键词,增加语义关联词
434 expanded_keywords = expand_search_keywords(keyword)
435 logger.info(f"扩展后的关键词: {expanded_keywords}") # 调试信息
436
437 # 构建查询条件
438 conditions = []
439 params = []
440
441 # 标题匹配 - 所有搜索模式都匹配title
442 conditions.append("title LIKE %s")
443 params.append(f"%{keyword}%")
444
445 # 为扩展关键词添加标题匹配条件
446 for exp_keyword in expanded_keywords:
447 if exp_keyword != keyword: # 避免重复原关键词
448 conditions.append("title LIKE %s")
449 params.append(f"%{exp_keyword}%")
450
451 # 描述匹配
452 if search_mode in ["title_desc", "all"]:
453 # 原始关键词匹配描述
454 conditions.append("content LIKE %s")
455 params.append(f"%{keyword}%")
456
457 # 扩展关键词匹配描述
458 for exp_keyword in expanded_keywords:
459 if exp_keyword != keyword:
460 conditions.append("content LIKE %s")
461 params.append(f"%{exp_keyword}%")
462
463 # 标签匹配
464 # 暂不处理,后续join实现
465
466 # 分类匹配 - 仅在all模式下
467 if search_mode == "all":
468 # 原始关键词匹配分类
469 conditions.append("topic_id LIKE %s")
470 params.append(f"%{keyword}%")
471
472 # 扩展关键词匹配分类
473 for exp_keyword in expanded_keywords:
474 if exp_keyword != keyword:
475 conditions.append("topic_id LIKE %s")
476 params.append(f"%{exp_keyword}%")
477
478 # 构建SQL查询
479 if conditions:
480 where_clause = " OR ".join(conditions)
481 logger.info(f"搜索条件: {where_clause}")
482 logger.info(f"参数列表: {params}")
483
484 if category:
485 where_clause = f"({where_clause}) AND topic_id=%s"
486 params.append(category)
487
488 sql = f"""
489 SELECT p.id, p.title, tp.name as category, p.heat, p.created_at, p.content,
490 GROUP_CONCAT(t.name) as tags
491 FROM posts p
492 LEFT JOIN post_tags pt ON p.id = pt.post_id
493 LEFT JOIN tags t ON pt.tag_id = t.id
494 LEFT JOIN topics tp ON p.topic_id = tp.id
495 WHERE {where_clause}
496 GROUP BY p.id
497 LIMIT 500
498 """
499
500 cursor.execute(sql, params)
501 expanded_results = cursor.fetchall()
502 logger.info(f"数据库返回记录数: {len(expanded_results) if expanded_results else 0}")
503 else:
504 expanded_results = []
505
506 # 如果扩展查询和精确匹配都没有结果,获取全部记录进行相关性计算
507 if not expanded_results and not exact_matches:
508 sql = "SELECT p.id, p.title, tp.name as category, p.heat, p.created_at, p.content, GROUP_CONCAT(t.name) as tags FROM posts p LEFT JOIN post_tags pt ON p.id = pt.post_id LEFT JOIN tags t ON pt.tag_id = t.id LEFT JOIN topics tp ON p.topic_id = tp.id"
509 if category:
510 sql += " WHERE p.topic_id=%s"
511 category_params = [category]
512 cursor.execute(sql + " GROUP BY p.id", category_params)
513 else:
514 cursor.execute(sql + " GROUP BY p.id")
515
516 all_results = cursor.fetchall() or [] # 确保返回列表
517 else:
518 if isinstance(exact_matches, tuple):
519 exact_matches = list(exact_matches)
520 if isinstance(expanded_results, tuple):
521 expanded_results = list(expanded_results)
522 all_results = expanded_results + exact_matches
523
524 # 对所有结果使用相关性计算规则
525 scored_results = []
526 for item in all_results:
527 # 计算相关性得分
528 relevance_score = calculate_keyword_relevance(keyword, item)
529
530 # 降低相关性阈值,确保更多结果被保留 (从0.5改为0.1)
531 if relevance_score > 0.1:
532 item['relevance_score'] = relevance_score
533 scored_results.append(item)
534 logger.info(f"匹配项: {item['title']}, 相关性得分: {relevance_score}")
535
536 # 按相关性得分排序
537 scored_results.sort(key=lambda x: x.get('relevance_score', 0), reverse=True)
538
539 # 确保精确匹配的结果置顶
540 if exact_matches:
541 for exact_match in exact_matches:
542 exact_match['relevance_score'] = 20.0 # 超高分确保置顶
543
544 # 移除scored_results中已经存在于exact_matches的项
545 exact_ids = {item['id'] for item in exact_matches}
546 scored_results = [item for item in scored_results if item['id'] not in exact_ids]
547
548 # 合并两个结果集
549 results = exact_matches + scored_results
550 else:
551 results = scored_results
552
553 # 限制返回结果数量
554 results = results[:50]
555
556 except Exception as e:
557 logger.error(f"搜索出错: {e}")
558 import traceback
559 traceback.print_exc()
560 return jsonify({"error": "搜索系统异常,请稍后再试"}), 500
561 finally:
562 conn.close()
563
564 # 第二阶段:根据指定方式排序
565 if results:
566 if sort_by == "similarity" or not sort_by:
567 # 保持按相关性得分排序,已经排好了
568 pass
569 elif sort_by == "downloads":
570 results.sort(key=lambda x: x.get("download_count", 0), reverse=True)
571 elif sort_by == "downloads_asc":
572 results.sort(key=lambda x: x.get("download_count", 0))
573 elif sort_by == "newest":
574 results.sort(key=lambda x: x.get("create_time", ""), reverse=True)
575 elif sort_by == "oldest":
576 results.sort(key=lambda x: x.get("create_time", ""))
577 elif sort_by == "title_asc":
578 results.sort(key=lambda x: x.get("title", ""))
579 elif sort_by == "title_desc":
580 results.sort(key=lambda x: x.get("title", ""), reverse=True)
581
582 # 最终处理:清理不需要返回的字段
583 for item in results:
584 item.pop("description", None)
585 item.pop("tags", None)
586 item.pop("relevance_score", None)
587
588 return Response(json.dumps({"results": results}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
589
590# 推荐功能的API
591@app.route('/recommend_tags', methods=['POST'])
592def recommend_tags():
593 """
594 推荐功能API
595 请求格式:{
596 "user_id": "user1",
597 "tags": ["标签1", "标签2"] # 可为空
598 }
599 """
600 if request.content_type != 'application/json':
601 return jsonify({"error": "Content-Type must be application/json"}), 415
602
603 data = request.get_json()
604 user_id = data.get("user_id")
605 tags = set(data.get("tags", []))
606
607 # 查询用户已保存的兴趣标签
608 user_tags = set()
609 if user_id:
610 conn = get_db_conn()
611 try:
612 with conn.cursor() as cursor:
613 cursor.execute("SELECT t.name FROM user_tags ut JOIN tags t ON ut.tag_id = t.id WHERE ut.user_id=%s", (user_id,))
614 user_tags = set(row[0] for row in cursor.fetchall())
615 finally:
616 conn.close()
617
618 # 合并前端传递的tags和用户兴趣标签
619 all_tags = list(tags | user_tags)
620
621 if not all_tags:
622 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
623
624 conn = get_db_conn()
625 try:
626 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
627 # 优先用tags字段匹配
628 # 先查找所有tag_id
629 tag_ids = []
630 for tag in all_tags:
631 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
632 row = cursor.fetchone()
633 if row:
634 tag_ids.append(row['id'])
635 if not tag_ids:
636 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
637 tag_placeholders = ','.join(['%s'] * len(tag_ids))
638 sql = f"""
639 SELECT p.id, p.title, tp.name as category, p.heat,
640 GROUP_CONCAT(tg.name) as tags
641 FROM posts p
642 LEFT JOIN post_tags pt ON p.id = pt.post_id
643 LEFT JOIN tags tg ON pt.tag_id = tg.id
644 LEFT JOIN topics tp ON p.topic_id = tp.id
645 WHERE pt.tag_id IN ({tag_placeholders})
646 GROUP BY p.id
647 LIMIT 50
648 """
649 cursor.execute(sql, tuple(tag_ids))
650 results = cursor.fetchall()
651 # 若无结果,回退title/content模糊匹配
652 if not results:
653 or_conditions = []
654 params = []
655 for tag in all_tags:
656 or_conditions.append("p.title LIKE %s OR p.content LIKE %s")
657 params.extend(['%' + tag + '%', '%' + tag + '%'])
658 where_clause = ' OR '.join(or_conditions)
659 sql = f"""
660 SELECT p.id, p.title, tp.name as category, p.heat,
661 GROUP_CONCAT(tg.name) as tags
662 FROM posts p
663 LEFT JOIN post_tags pt ON p.id = pt.post_id
664 LEFT JOIN tags tg ON pt.tag_id = tg.id
665 LEFT JOIN topics tp ON p.topic_id = tp.id
666 WHERE {where_clause}
667 GROUP BY p.id
668 LIMIT 50
669 """
670 cursor.execute(sql, tuple(params))
671 results = cursor.fetchall()
672 finally:
673 conn.close()
674
675 if not results:
676 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
677
678 return Response(json.dumps({"recommendations": results}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
679
680# 用户兴趣标签管理API(可选)
681@app.route('/tags', methods=['POST', 'GET', 'DELETE'])
682def user_tags():
683 """
684 POST: 添加用户兴趣标签
685 GET: 查询用户兴趣标签
686 DELETE: 删除用户兴趣标签
687 """
688 if request.method == 'POST':
689 if request.content_type != 'application/json':
690 return jsonify({"error": "Content-Type must be application/json"}), 415
691 data = request.get_json()
692 user_id = data.get("user_id")
693 tags = data.get("tags", [])
694
695 if not user_id:
696 return jsonify({"error": "用户ID不能为空"}), 400
697
698 # 确保标签列表格式正确
699 if isinstance(tags, str):
700 tags = [tag.strip() for tag in tags.split(',') if tag.strip()]
701
702 if not tags:
703 return jsonify({"error": "标签不能为空"}), 400
704
705 conn = get_db_conn()
706 try:
707 with conn.cursor() as cursor:
708 # 添加用户标签
709 for tag in tags:
710 # 先查找tag_id
711 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
712 tag_row = cursor.fetchone()
713 if tag_row:
714 tag_id = tag_row[0]
715 cursor.execute("REPLACE INTO user_tags (user_id, tag_id) VALUES (%s, %s)", (user_id, tag_id))
716 conn.commit()
717 # 返回更新后的标签列表
718 cursor.execute("SELECT t.name FROM user_tags ut JOIN tags t ON ut.tag_id = t.id WHERE ut.user_id=%s", (user_id,))
719 updated_tags = [row[0] for row in cursor.fetchall()]
720 finally:
721 conn.close()
722 return Response(json.dumps({"msg": "添加成功", "tags": updated_tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
723 elif request.method == 'DELETE':
724 if request.content_type != 'application/json':
725 return jsonify({"error": "Content-Type must be application/json"}), 415
726 data = request.get_json()
727 user_id = data.get("user_id")
728 tags = data.get("tags", [])
729 if not user_id:
730 return jsonify({"error": "用户ID不能为空"}), 400
731 if not tags:
732 return jsonify({"error": "标签不能为空"}), 400
733
734 conn = get_db_conn()
735 try:
736 with conn.cursor() as cursor:
737 for tag in tags:
738 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
739 tag_row = cursor.fetchone()
740 if tag_row:
741 tag_id = tag_row[0]
742 cursor.execute("DELETE FROM user_tags WHERE user_id=%s AND tag_id=%s", (user_id, tag_id))
743 conn.commit()
744 cursor.execute("SELECT t.name FROM user_tags ut JOIN tags t ON ut.tag_id = t.id WHERE ut.user_id=%s", (user_id,))
745 remaining_tags = [row[0] for row in cursor.fetchall()]
746 finally:
747 conn.close()
748 return Response(json.dumps({"msg": "删除成功", "tags": remaining_tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
749 else: # GET 请求
750 user_id = request.args.get("user_id")
751 if not user_id:
752 return jsonify({"error": "用户ID不能为空"}), 400
753 conn = get_db_conn()
754 try:
755 with conn.cursor() as cursor:
756 cursor.execute("SELECT t.name FROM user_tags ut JOIN tags t ON ut.tag_id = t.id WHERE ut.user_id=%s", (user_id,))
757 tags = [row[0] for row in cursor.fetchall()]
758 finally:
759 conn.close()
760 return Response(json.dumps({"tags": tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
761
762# 添加/user_tags路由作为/tags的别名
763@app.route('/user_tags', methods=['POST', 'GET', 'DELETE'])
764def user_tags_alias():
765 """
766 /user_tags路由 - 作为/tags路由的别名
767 POST: 添加用户兴趣标签
768 GET: 查询用户兴趣标签
769 DELETE: 删除用户兴趣标签
770 """
771 return user_tags()
772
773# 基于用户的协同过滤推荐API
774@app.route('/user_based_recommend', methods=['POST'])
775def user_based_recommend():
776 """
777 基于用户的协同过滤推荐API
778 请求格式:{
779 "user_id": "user1",
780 "top_n": 5
781 }
782 """
783 if request.content_type != 'application/json':
784 return jsonify({"error": "Content-Type must be application/json"}), 415
785
786 data = request.get_json()
787 user_id = data.get("user_id")
788 top_n = int(data.get("top_n", 5))
789
790 if not user_id:
791 return jsonify({"error": "用户ID不能为空"}), 400
792
793 conn = get_db_conn()
794 try:
795 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
796 # 1. 检查用户是否存在下载记录(收藏或浏览)
797 cursor.execute("""
798 SELECT COUNT(*) as count
799 FROM behaviors
800 WHERE user_id = %s AND type IN ('favorite', 'view')
801 """, (user_id,))
802 result = cursor.fetchone()
803 user_download_count = result['count'] if result else 0
804
805 logger.info(f"用户 {user_id} 下载记录数: {user_download_count}")
806
807 # 如果用户没有足够的行为数据,返回基于热度的推荐
808 if user_download_count < 3:
809 logger.info(f"用户 {user_id} 下载记录不足,返回热门推荐")
810 cursor.execute("""
811 SELECT p.id, p.title, tp.name as category, p.heat
812 FROM posts p
813 LEFT JOIN topics tp ON p.topic_id = tp.id
814 ORDER BY p.heat DESC
815 LIMIT %s
816 """, (top_n,))
817 popular_seeds = cursor.fetchall()
818 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
819
820 # 2. 获取用户已下载(收藏/浏览)的帖子
821 cursor.execute("""
822 SELECT post_id
823 FROM behaviors
824 WHERE user_id = %s AND type IN ('favorite', 'view')
825 """, (user_id,))
826 user_seeds = set(row['post_id'] for row in cursor.fetchall())
827 logger.info(f"用户 {user_id} 已下载种子: {user_seeds}")
828
829 # 3. 获取所有用户-帖子下载(收藏/浏览)矩阵
830 cursor.execute("""
831 SELECT user_id, post_id
832 FROM behaviors
833 WHERE created_at > DATE_SUB(NOW(), INTERVAL 3 MONTH)
834 AND user_id <> %s AND type IN ('favorite', 'view')
835 """, (user_id,))
836 download_records = cursor.fetchall()
837
838 if not download_records:
839 logger.info(f"没有其他用户的下载记录,返回热门推荐")
840 cursor.execute("""
841 SELECT p.id, p.title, tp.name as category, p.heat
842 FROM posts p
843 LEFT JOIN topics tp ON p.topic_id = tp.id
844 ORDER BY p.heat DESC
845 LIMIT %s
846 """, (top_n,))
847 popular_seeds = cursor.fetchall()
848 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
849
850 # 构建用户-物品矩阵
851 user_item_matrix = {}
852 for record in download_records:
853 uid = record['user_id']
854 sid = record['post_id']
855 if uid not in user_item_matrix:
856 user_item_matrix[uid] = set()
857 user_item_matrix[uid].add(sid)
858
859 # 4. 计算用户相似度
860 similar_users = []
861 for other_id, other_seeds in user_item_matrix.items():
862 if other_id == user_id:
863 continue
864 intersection = len(user_seeds.intersection(other_seeds))
865 union = len(user_seeds.union(other_seeds))
866 if union > 0 and intersection > 0:
867 similarity = intersection / union
868 similar_users.append((other_id, similarity, other_seeds))
869 logger.info(f"找到 {len(similar_users)} 个相似用户")
870 similar_users.sort(key=lambda x: x[1], reverse=True)
871 similar_users = similar_users[:5]
872 # 5. 基于相似用户推荐帖子
873 candidate_seeds = {}
874 for similar_user, similarity, seeds in similar_users:
875 logger.info(f"相似用户 {similar_user}, 相似度 {similarity}")
876 for post_id in seeds:
877 if post_id not in user_seeds:
878 if post_id not in candidate_seeds:
879 candidate_seeds[post_id] = 0
880 candidate_seeds[post_id] += similarity
881 if not candidate_seeds:
882 logger.info(f"没有找到候选种子,返回热门推荐")
883 cursor.execute("""
884 SELECT p.id, p.title, tp.name as category, p.heat
885 FROM posts p
886 LEFT JOIN topics tp ON p.topic_id = tp.id
887 ORDER BY p.heat DESC
888 LIMIT %s
889 """, (top_n,))
890 popular_seeds = cursor.fetchall()
891 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
892 # 6. 获取推荐帖子的详细信息
893 recommended_seeds = sorted(candidate_seeds.items(), key=lambda x: x[1], reverse=True)[:top_n]
894 post_ids = [post_id for post_id, _ in recommended_seeds]
895 format_strings = ','.join(['%s'] * len(post_ids))
896 cursor.execute(f"""
897 SELECT p.id, p.title, tp.name as category, p.heat
898 FROM posts p
899 LEFT JOIN topics tp ON p.topic_id = tp.id
900 WHERE p.id IN ({format_strings})
901 """, tuple(post_ids))
902 result_seeds = cursor.fetchall()
903 seed_score_map = {post_id: score for post_id, score in recommended_seeds}
904 result_seeds.sort(key=lambda x: seed_score_map.get(x['id'], 0), reverse=True)
905 logger.info(f"返回 {len(result_seeds)} 个基于协同过滤的推荐")
906 return Response(json.dumps({"recommendations": result_seeds, "type": "collaborative"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
907 except Exception as e:
908 logger.error(f"推荐系统错误: {e}")
909 import traceback
910 traceback.print_exc()
911 return Response(json.dumps({"error": "推荐系统异常,请稍后再试", "details": str(e)}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
912 finally:
913 conn.close()
914@app.route('/word2vec_status', methods=['GET'])
915def word2vec_status():
916 """
917 检查Word2Vec模型状态
918 返回模型是否加载、词汇量等信息
919 """
920 if not WORD2VEC_ENABLED:
921 return Response(json.dumps({
922 "enabled": False,
923 "message": "Word2Vec功能未启用"
924 }, ensure_ascii=False), mimetype='application/json; charset=utf-8')
925 try:
926 helper = get_word2vec_helper()
927 status = {
928 "enabled": WORD2VEC_ENABLED,
929 "initialized": helper.initialized,
930 "vocab_size": len(helper.model.index_to_key) if helper.model else 0,
931 "vector_size": helper.model.vector_size if helper.model else 0
932 }
933
934 # 测试几个常用词的相似词,展示模型效果
935 test_results = {}
936 test_words = ["电影", "动作", "科幻", "动漫", "游戏"]
937 for word in test_words:
938 similar_words = helper.get_similar_words(word, topn=5)
939 test_results[word] = similar_words
940
941 status["test_results"] = test_results
942 return Response(json.dumps(status, ensure_ascii=False), mimetype='application/json; charset=utf-8')
943 except Exception as e:
944 return Response(json.dumps({
945 "enabled": WORD2VEC_ENABLED,
946 "initialized": False,
947 "error": str(e)
948 }, ensure_ascii=False), mimetype='application/json; charset=utf-8')
949
950# 添加一个临时诊断端点
951@app.route('/debug_search', methods=['POST'])
952def debug_search():
953 """临时的调试端点,用于检查数据库中的记录"""
954 if request.content_type != 'application/json':
955 return jsonify({"error": "Content-Type must be application/json"}), 415
956
957 data = request.get_json()
958 keyword = data.get("keyword", "").strip()
959
960 conn = get_db_conn()
961 try:
962 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
963 # 尝试查询包含特定词的所有记录
964 queries = [
965 ("标题中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE title LIKE '%{keyword}%' LIMIT 10"),
966 ("描述中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE description LIKE '%{keyword}%' LIMIT 10"),
967 ("标签中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE FIND_IN_SET('{keyword}', tags) LIMIT 10"),
968 ("肖申克的救赎", "SELECT seed_id, title, description, tags FROM pt_seed WHERE title = '肖申克的救赎'")
969 ]
970
971 results = {}
972 for query_name, query in queries:
973 cursor.execute(query)
974 results[query_name] = cursor.fetchall()
975
976 return Response(json.dumps(results, ensure_ascii=False), mimetype='application/json; charset=utf-8')
977 finally:
978 conn.close()
979
980"""
981接口本地测试方法(可直接运行main_online.py后用curl或Postman测试):
982
9831. 搜索接口
984curl -X POST http://127.0.0.1:5000/search -H "Content-Type: application/json" -d '{"keyword":"电影","sort_by":"downloads"}'
985
9862. 标签推荐接口
987curl -X POST http://127.0.0.1:5000/recommend_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
988
9893. 用户兴趣标签管理(添加标签)
990curl -X POST http://127.0.0.1:5000/user_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
991
9924. 用户兴趣标签管理(查询标签)
993curl "http://127.0.0.1:5000/user_tags?user_id=1"
994
9955. 用户兴趣标签管理(删除标签)
996curl -X DELETE http://127.0.0.1:5000/user_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
997
9986. 协同过滤推荐
999curl -X POST http://127.0.0.1:5000/user_based_recommend -H "Content-Type: application/json" -d '{"user_id":"user1","top_n":3}'
1000
10017. Word2Vec状态检查
1002curl "http://127.0.0.1:5000/word2vec_status"
1003
10048. 调试接口(临时)
1005curl -X POST http://127.0.0.1:5000/debug_search -H "Content-Type: application/json" -d '{"keyword":"电影"}'
1006
1007所有接口均可用Postman按上述参数测试。
1008"""
1009
1010if __name__ == "__main__":
1011 try:
1012 logger.info("搜索推荐服务启动中...")
1013 app.run(host="0.0.0.0", port=5000)
1014 except Exception as e:
1015 logger.error(f"启动异常: {e}")
1016 import traceback
1017 traceback.print_exc()