blob: f8fdc070ae8f07b71d6ead35a5e505db0632b038 [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
22301008af173152025-06-15 10:46:25 +0800582 # 最终处理:清理不需要返回的字段,并将 datetime 转为字符串
22301008cae762d2025-06-14 00:27:04 +0800583 for item in results:
584 item.pop("description", None)
585 item.pop("tags", None)
586 item.pop("relevance_score", None)
22301008af173152025-06-15 10:46:25 +0800587 for k, v in item.items():
588 if hasattr(v, 'isoformat'):
589 item[k] = v.isoformat(sep=' ', timespec='seconds')
22301008cae762d2025-06-14 00:27:04 +0800590
591 return Response(json.dumps({"results": results}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
592
593# 推荐功能的API
594@app.route('/recommend_tags', methods=['POST'])
595def recommend_tags():
596 """
597 推荐功能API
598 请求格式:{
599 "user_id": "user1",
600 "tags": ["标签1", "标签2"] # 可为空
601 }
602 """
603 if request.content_type != 'application/json':
604 return jsonify({"error": "Content-Type must be application/json"}), 415
605
606 data = request.get_json()
607 user_id = data.get("user_id")
608 tags = set(data.get("tags", []))
609
610 # 查询用户已保存的兴趣标签
611 user_tags = set()
612 if user_id:
613 conn = get_db_conn()
614 try:
615 with conn.cursor() as cursor:
616 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,))
617 user_tags = set(row[0] for row in cursor.fetchall())
618 finally:
619 conn.close()
620
621 # 合并前端传递的tags和用户兴趣标签
622 all_tags = list(tags | user_tags)
623
624 if not all_tags:
625 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
626
627 conn = get_db_conn()
628 try:
629 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
630 # 优先用tags字段匹配
631 # 先查找所有tag_id
632 tag_ids = []
633 for tag in all_tags:
634 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
635 row = cursor.fetchone()
636 if row:
637 tag_ids.append(row['id'])
638 if not tag_ids:
639 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
640 tag_placeholders = ','.join(['%s'] * len(tag_ids))
641 sql = f"""
642 SELECT p.id, p.title, tp.name as category, p.heat,
643 GROUP_CONCAT(tg.name) as tags
644 FROM posts p
645 LEFT JOIN post_tags pt ON p.id = pt.post_id
646 LEFT JOIN tags tg ON pt.tag_id = tg.id
647 LEFT JOIN topics tp ON p.topic_id = tp.id
648 WHERE pt.tag_id IN ({tag_placeholders})
649 GROUP BY p.id
650 LIMIT 50
651 """
652 cursor.execute(sql, tuple(tag_ids))
653 results = cursor.fetchall()
654 # 若无结果,回退title/content模糊匹配
655 if not results:
656 or_conditions = []
657 params = []
658 for tag in all_tags:
659 or_conditions.append("p.title LIKE %s OR p.content LIKE %s")
660 params.extend(['%' + tag + '%', '%' + tag + '%'])
661 where_clause = ' OR '.join(or_conditions)
662 sql = f"""
663 SELECT p.id, p.title, tp.name as category, p.heat,
664 GROUP_CONCAT(tg.name) as tags
665 FROM posts p
666 LEFT JOIN post_tags pt ON p.id = pt.post_id
667 LEFT JOIN tags tg ON pt.tag_id = tg.id
668 LEFT JOIN topics tp ON p.topic_id = tp.id
669 WHERE {where_clause}
670 GROUP BY p.id
671 LIMIT 50
672 """
673 cursor.execute(sql, tuple(params))
674 results = cursor.fetchall()
675 finally:
676 conn.close()
677
678 if not results:
679 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
680
681 return Response(json.dumps({"recommendations": results}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
682
683# 用户兴趣标签管理API(可选)
684@app.route('/tags', methods=['POST', 'GET', 'DELETE'])
685def user_tags():
686 """
687 POST: 添加用户兴趣标签
688 GET: 查询用户兴趣标签
689 DELETE: 删除用户兴趣标签
690 """
691 if request.method == 'POST':
692 if request.content_type != 'application/json':
693 return jsonify({"error": "Content-Type must be application/json"}), 415
694 data = request.get_json()
695 user_id = data.get("user_id")
696 tags = data.get("tags", [])
697
698 if not user_id:
699 return jsonify({"error": "用户ID不能为空"}), 400
700
701 # 确保标签列表格式正确
702 if isinstance(tags, str):
703 tags = [tag.strip() for tag in tags.split(',') if tag.strip()]
704
705 if not tags:
706 return jsonify({"error": "标签不能为空"}), 400
707
708 conn = get_db_conn()
709 try:
710 with conn.cursor() as cursor:
711 # 添加用户标签
712 for tag in tags:
713 # 先查找tag_id
714 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
715 tag_row = cursor.fetchone()
716 if tag_row:
717 tag_id = tag_row[0]
718 cursor.execute("REPLACE INTO user_tags (user_id, tag_id) VALUES (%s, %s)", (user_id, tag_id))
719 conn.commit()
720 # 返回更新后的标签列表
721 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,))
722 updated_tags = [row[0] for row in cursor.fetchall()]
723 finally:
724 conn.close()
725 return Response(json.dumps({"msg": "添加成功", "tags": updated_tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
726 elif request.method == 'DELETE':
727 if request.content_type != 'application/json':
728 return jsonify({"error": "Content-Type must be application/json"}), 415
729 data = request.get_json()
730 user_id = data.get("user_id")
731 tags = data.get("tags", [])
732 if not user_id:
733 return jsonify({"error": "用户ID不能为空"}), 400
734 if not tags:
735 return jsonify({"error": "标签不能为空"}), 400
736
737 conn = get_db_conn()
738 try:
739 with conn.cursor() as cursor:
740 for tag in tags:
741 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
742 tag_row = cursor.fetchone()
743 if tag_row:
744 tag_id = tag_row[0]
745 cursor.execute("DELETE FROM user_tags WHERE user_id=%s AND tag_id=%s", (user_id, tag_id))
746 conn.commit()
747 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,))
748 remaining_tags = [row[0] for row in cursor.fetchall()]
749 finally:
750 conn.close()
751 return Response(json.dumps({"msg": "删除成功", "tags": remaining_tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
752 else: # GET 请求
753 user_id = request.args.get("user_id")
754 if not user_id:
755 return jsonify({"error": "用户ID不能为空"}), 400
756 conn = get_db_conn()
757 try:
758 with conn.cursor() as cursor:
759 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,))
760 tags = [row[0] for row in cursor.fetchall()]
761 finally:
762 conn.close()
763 return Response(json.dumps({"tags": tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
764
765# 添加/user_tags路由作为/tags的别名
766@app.route('/user_tags', methods=['POST', 'GET', 'DELETE'])
767def user_tags_alias():
768 """
769 /user_tags路由 - 作为/tags路由的别名
770 POST: 添加用户兴趣标签
771 GET: 查询用户兴趣标签
772 DELETE: 删除用户兴趣标签
773 """
774 return user_tags()
775
776# 基于用户的协同过滤推荐API
777@app.route('/user_based_recommend', methods=['POST'])
778def user_based_recommend():
779 """
780 基于用户的协同过滤推荐API
781 请求格式:{
782 "user_id": "user1",
783 "top_n": 5
784 }
785 """
786 if request.content_type != 'application/json':
787 return jsonify({"error": "Content-Type must be application/json"}), 415
788
789 data = request.get_json()
790 user_id = data.get("user_id")
791 top_n = int(data.get("top_n", 5))
792
793 if not user_id:
794 return jsonify({"error": "用户ID不能为空"}), 400
795
796 conn = get_db_conn()
797 try:
798 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
799 # 1. 检查用户是否存在下载记录(收藏或浏览)
800 cursor.execute("""
801 SELECT COUNT(*) as count
802 FROM behaviors
803 WHERE user_id = %s AND type IN ('favorite', 'view')
804 """, (user_id,))
805 result = cursor.fetchone()
806 user_download_count = result['count'] if result else 0
807
808 logger.info(f"用户 {user_id} 下载记录数: {user_download_count}")
809
810 # 如果用户没有足够的行为数据,返回基于热度的推荐
811 if user_download_count < 3:
812 logger.info(f"用户 {user_id} 下载记录不足,返回热门推荐")
813 cursor.execute("""
814 SELECT p.id, p.title, tp.name as category, p.heat
815 FROM posts p
816 LEFT JOIN topics tp ON p.topic_id = tp.id
817 ORDER BY p.heat DESC
818 LIMIT %s
819 """, (top_n,))
820 popular_seeds = cursor.fetchall()
821 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
822
823 # 2. 获取用户已下载(收藏/浏览)的帖子
824 cursor.execute("""
825 SELECT post_id
826 FROM behaviors
827 WHERE user_id = %s AND type IN ('favorite', 'view')
828 """, (user_id,))
829 user_seeds = set(row['post_id'] for row in cursor.fetchall())
830 logger.info(f"用户 {user_id} 已下载种子: {user_seeds}")
831
832 # 3. 获取所有用户-帖子下载(收藏/浏览)矩阵
833 cursor.execute("""
834 SELECT user_id, post_id
835 FROM behaviors
836 WHERE created_at > DATE_SUB(NOW(), INTERVAL 3 MONTH)
837 AND user_id <> %s AND type IN ('favorite', 'view')
838 """, (user_id,))
839 download_records = cursor.fetchall()
840
841 if not download_records:
842 logger.info(f"没有其他用户的下载记录,返回热门推荐")
843 cursor.execute("""
844 SELECT p.id, p.title, tp.name as category, p.heat
845 FROM posts p
846 LEFT JOIN topics tp ON p.topic_id = tp.id
847 ORDER BY p.heat DESC
848 LIMIT %s
849 """, (top_n,))
850 popular_seeds = cursor.fetchall()
851 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
852
853 # 构建用户-物品矩阵
854 user_item_matrix = {}
855 for record in download_records:
856 uid = record['user_id']
857 sid = record['post_id']
858 if uid not in user_item_matrix:
859 user_item_matrix[uid] = set()
860 user_item_matrix[uid].add(sid)
861
862 # 4. 计算用户相似度
863 similar_users = []
864 for other_id, other_seeds in user_item_matrix.items():
865 if other_id == user_id:
866 continue
867 intersection = len(user_seeds.intersection(other_seeds))
868 union = len(user_seeds.union(other_seeds))
869 if union > 0 and intersection > 0:
870 similarity = intersection / union
871 similar_users.append((other_id, similarity, other_seeds))
872 logger.info(f"找到 {len(similar_users)} 个相似用户")
873 similar_users.sort(key=lambda x: x[1], reverse=True)
874 similar_users = similar_users[:5]
875 # 5. 基于相似用户推荐帖子
876 candidate_seeds = {}
877 for similar_user, similarity, seeds in similar_users:
878 logger.info(f"相似用户 {similar_user}, 相似度 {similarity}")
879 for post_id in seeds:
880 if post_id not in user_seeds:
881 if post_id not in candidate_seeds:
882 candidate_seeds[post_id] = 0
883 candidate_seeds[post_id] += similarity
884 if not candidate_seeds:
885 logger.info(f"没有找到候选种子,返回热门推荐")
886 cursor.execute("""
887 SELECT p.id, p.title, tp.name as category, p.heat
888 FROM posts p
889 LEFT JOIN topics tp ON p.topic_id = tp.id
890 ORDER BY p.heat DESC
891 LIMIT %s
892 """, (top_n,))
893 popular_seeds = cursor.fetchall()
894 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
895 # 6. 获取推荐帖子的详细信息
896 recommended_seeds = sorted(candidate_seeds.items(), key=lambda x: x[1], reverse=True)[:top_n]
897 post_ids = [post_id for post_id, _ in recommended_seeds]
898 format_strings = ','.join(['%s'] * len(post_ids))
899 cursor.execute(f"""
900 SELECT p.id, p.title, tp.name as category, p.heat
901 FROM posts p
902 LEFT JOIN topics tp ON p.topic_id = tp.id
903 WHERE p.id IN ({format_strings})
904 """, tuple(post_ids))
905 result_seeds = cursor.fetchall()
906 seed_score_map = {post_id: score for post_id, score in recommended_seeds}
907 result_seeds.sort(key=lambda x: seed_score_map.get(x['id'], 0), reverse=True)
908 logger.info(f"返回 {len(result_seeds)} 个基于协同过滤的推荐")
909 return Response(json.dumps({"recommendations": result_seeds, "type": "collaborative"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
910 except Exception as e:
911 logger.error(f"推荐系统错误: {e}")
912 import traceback
913 traceback.print_exc()
914 return Response(json.dumps({"error": "推荐系统异常,请稍后再试", "details": str(e)}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
915 finally:
916 conn.close()
917@app.route('/word2vec_status', methods=['GET'])
918def word2vec_status():
919 """
920 检查Word2Vec模型状态
921 返回模型是否加载、词汇量等信息
922 """
923 if not WORD2VEC_ENABLED:
924 return Response(json.dumps({
925 "enabled": False,
926 "message": "Word2Vec功能未启用"
927 }, ensure_ascii=False), mimetype='application/json; charset=utf-8')
928 try:
929 helper = get_word2vec_helper()
930 status = {
931 "enabled": WORD2VEC_ENABLED,
932 "initialized": helper.initialized,
933 "vocab_size": len(helper.model.index_to_key) if helper.model else 0,
934 "vector_size": helper.model.vector_size if helper.model else 0
935 }
936
937 # 测试几个常用词的相似词,展示模型效果
938 test_results = {}
939 test_words = ["电影", "动作", "科幻", "动漫", "游戏"]
940 for word in test_words:
941 similar_words = helper.get_similar_words(word, topn=5)
942 test_results[word] = similar_words
943
944 status["test_results"] = test_results
945 return Response(json.dumps(status, ensure_ascii=False), mimetype='application/json; charset=utf-8')
946 except Exception as e:
947 return Response(json.dumps({
948 "enabled": WORD2VEC_ENABLED,
949 "initialized": False,
950 "error": str(e)
951 }, ensure_ascii=False), mimetype='application/json; charset=utf-8')
952
953# 添加一个临时诊断端点
954@app.route('/debug_search', methods=['POST'])
955def debug_search():
956 """临时的调试端点,用于检查数据库中的记录"""
957 if request.content_type != 'application/json':
958 return jsonify({"error": "Content-Type must be application/json"}), 415
959
960 data = request.get_json()
961 keyword = data.get("keyword", "").strip()
962
963 conn = get_db_conn()
964 try:
965 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
966 # 尝试查询包含特定词的所有记录
967 queries = [
968 ("标题中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE title LIKE '%{keyword}%' LIMIT 10"),
969 ("描述中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE description LIKE '%{keyword}%' LIMIT 10"),
970 ("标签中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE FIND_IN_SET('{keyword}', tags) LIMIT 10"),
971 ("肖申克的救赎", "SELECT seed_id, title, description, tags FROM pt_seed WHERE title = '肖申克的救赎'")
972 ]
973
974 results = {}
975 for query_name, query in queries:
976 cursor.execute(query)
977 results[query_name] = cursor.fetchall()
978
979 return Response(json.dumps(results, ensure_ascii=False), mimetype='application/json; charset=utf-8')
980 finally:
981 conn.close()
982
983"""
984接口本地测试方法(可直接运行main_online.py后用curl或Postman测试):
985
9861. 搜索接口
987curl -X POST http://127.0.0.1:5000/search -H "Content-Type: application/json" -d '{"keyword":"电影","sort_by":"downloads"}'
988
9892. 标签推荐接口
990curl -X POST http://127.0.0.1:5000/recommend_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
991
9923. 用户兴趣标签管理(添加标签)
993curl -X POST http://127.0.0.1:5000/user_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
994
9954. 用户兴趣标签管理(查询标签)
996curl "http://127.0.0.1:5000/user_tags?user_id=1"
997
9985. 用户兴趣标签管理(删除标签)
999curl -X DELETE http://127.0.0.1:5000/user_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
1000
10016. 协同过滤推荐
1002curl -X POST http://127.0.0.1:5000/user_based_recommend -H "Content-Type: application/json" -d '{"user_id":"user1","top_n":3}'
1003
10047. Word2Vec状态检查
1005curl "http://127.0.0.1:5000/word2vec_status"
1006
10078. 调试接口(临时)
1008curl -X POST http://127.0.0.1:5000/debug_search -H "Content-Type: application/json" -d '{"keyword":"电影"}'
1009
1010所有接口均可用Postman按上述参数测试。
1011"""
1012
1013if __name__ == "__main__":
1014 try:
1015 logger.info("搜索推荐服务启动中...")
1016 app.run(host="0.0.0.0", port=5000)
1017 except Exception as e:
1018 logger.error(f"启动异常: {e}")
1019 import traceback
1020 traceback.print_exc()