blob: bd7e1be899f5f3e9ccd3123ce7cbc7995fcf292f [file] [log] [blame]
95630366980c1f272025-06-20 14:08:54 +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 for exp_keyword in expanded_keywords:
344 if exp_keyword != keyword and exp_keyword in title: # 避免重复计算原关键词
345 score += 1.5 # 一般语义关联
346
347 return score
348
349# 创建Flask应用
350app = Flask(__name__)
351CORS(app) # 允许所有跨域请求
352
353# 添加init_word2vec函数
354def init_word2vec():
355 """初始化Word2Vec模型"""
356 try:
357 helper = get_word2vec_helper()
358 if helper.initialized:
359 logger.info(f"Word2Vec模型已成功加载,词汇量: {len(helper.model.index_to_key)}, 向量维度: {helper.model.vector_size}")
360 else:
361 if helper.load_model():
362 logger.info(f"Word2Vec模型加载成功,词汇量: {len(helper.model.index_to_key)}, 向量维度: {helper.model.vector_size}")
363 else:
364 logger.error("Word2Vec模型加载失败")
365 except Exception as e:
366 logger.error(f"初始化Word2Vec出错: {e}")
367
368# 新的初始化方式:
369def initialize_app():
370 """应用初始化函数,替代before_first_request装饰器"""
371 # 修正:使用正确的函数名
372 # 原代码: init_semantic_mapping()
373 # 修正为使用已定义的函数名
374 global SEMANTIC_MAPPINGS
375 SEMANTIC_MAPPINGS = load_semantic_mappings() # 更新全局语义映射变量
376
377 if WORD2VEC_ENABLED:
378 init_word2vec() # 现在这个函数已经定义了
379
380# 在启动应用之前调用初始化函数
381initialize_app()
382
383# 测试路由
384@app.route('/test', methods=['GET'])
385def test():
386 import datetime
387 return jsonify({"message": "服务器正常运行", "timestamp": str(datetime.datetime.now())})
388
389# 获取单个帖子详情的API
390@app.route('/post/<int:post_id>', methods=['GET'])
391def get_post_detail(post_id):
392 """
393 获取单个帖子详情
394 """
395 logger.info(f"接收到获取帖子详情请求,post_id: {post_id}")
396 conn = get_db_conn()
397 try:
398 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
399 # 联表查询帖子详情,获取分类名和type
400 query = """
401 SELECT
402 p.id,
403 p.title,
404 p.content,
405 p.heat,
406 p.created_at as create_time,
407 p.updated_at as last_active,
408 p.status,
409 p.type,
410 tp.name as category
411 FROM posts p
412 LEFT JOIN topics tp ON p.topic_id = tp.id
413 WHERE p.id = %s
414 """
415 logger.info(f"执行查询: {query} with post_id: {post_id}")
416 cursor.execute(query, (post_id,))
417 post = cursor.fetchone()
418
419 logger.info(f"查询结果: {post}")
420
421 if not post:
422 logger.warning(f"帖子不存在,post_id: {post_id}")
423 return jsonify({"error": "帖子不存在"}), 404
424
425 # 设置默认值
426 post['tags'] = []
427 post['author'] = '匿名用户'
428 if not post.get('category'):
429 post['category'] = '未分类'
430 if not post.get('type'):
431 post['type'] = 'text'
432 # 格式化时间
433 if post['create_time']:
434 post['create_time'] = post['create_time'].strftime('%Y-%m-%d %H:%M:%S')
435 if post['last_active']:
436 post['last_active'] = post['last_active'].strftime('%Y-%m-%d %H:%M:%S')
437
438 logger.info(f"返回帖子详情: {post}")
439 return Response(json.dumps(post, ensure_ascii=False), mimetype='application/json; charset=utf-8')
440 except Exception as e:
441 logger.error(f"获取帖子详情失败: {e}")
442 import traceback
443 traceback.print_exc()
444 return jsonify({"error": "服务器内部错误"}), 500
445 finally:
446 conn.close()
447
448# 搜索功能的API
449@app.route('/search', methods=['POST'])
450def search():
451 """
452 搜索功能API
453 请求格式:{
454 "keyword": "关键词",
455 "sort_by": "downloads" | "downloads_asc" | "newest" | "oldest" | "similarity" | "title_asc" | "title_desc",
456 "category": "可选,分类名",
457 "search_mode": "title" | "title_desc" | "tags" | "all" # 可选,默认"title",
458 "tags": ["标签1", "标签2"] # 可选,支持传递多个标签
459 }
460 """
461 if request.content_type != 'application/json':
462 return jsonify({"error": "Content-Type must be application/json"}), 415
463
464 data = request.get_json()
465 keyword = data.get("keyword", "").strip()
466 sort_by = data.get("sort_by", "similarity") # 默认按相似度排序
467 category = data.get("category", None)
468 search_mode = data.get("search_mode", "title")
469 tags = data.get("tags", None) # 支持传递多个标签
470
471 # 校验参数 - 不管什么模式都要求关键词
472 if not (1 <= len(keyword) <= 20):
473 return jsonify({"error": "请输入1-20个字符"}), 400
474
475 # 第一阶段:数据库查询获取候选集
476 results = []
477 conn = get_db_conn()
478 try:
479 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
480 # 首先尝试查询完全匹配的结果
481 exact_query = f"""
482 SELECT id, title, topic_id, heat, created_at, content
483 FROM posts
484 WHERE title = %s
485 """
486 cursor.execute(exact_query, (keyword,))
487 exact_matches = cursor.fetchall() or [] # 确保返回列表而非元组
488
489 # 扩展关键词,增加语义关联词
490 expanded_keywords = expand_search_keywords(keyword)
491 logger.info(f"扩展后的关键词: {expanded_keywords}") # 调试信息
492
493 # 构建查询条件
494 conditions = []
495 params = []
496
497 # 标题匹配 - 所有搜索模式都匹配title
498 conditions.append("title LIKE %s")
499 params.append(f"%{keyword}%")
500
501 # 为扩展关键词添加标题匹配条件
502 for exp_keyword in expanded_keywords:
503 if exp_keyword != keyword: # 避免重复原关键词
504 conditions.append("title LIKE %s")
505 params.append(f"%{exp_keyword}%")
506
507 # 描述匹配
508 if search_mode in ["title_desc", "all"]:
509 # 原始关键词匹配描述
510 conditions.append("content LIKE %s")
511 params.append(f"%{keyword}%")
512
513 # 扩展关键词匹配描述
514 for exp_keyword in expanded_keywords:
515 if exp_keyword != keyword:
516 conditions.append("content LIKE %s")
517 params.append(f"%{exp_keyword}%")
518
519 # 标签匹配
520 # 暂不处理,后续join实现
521
522 # 分类匹配 - 仅在all模式下
523 if search_mode == "all":
524 # 原始关键词匹配分类
525 conditions.append("topic_id LIKE %s")
526 params.append(f"%{keyword}%")
527
528 # 扩展关键词匹配分类
529 for exp_keyword in expanded_keywords:
530 if exp_keyword != keyword:
531 conditions.append("topic_id LIKE %s")
532 params.append(f"%{exp_keyword}%")
533
534 # 构建SQL查询
535 if conditions:
536 where_clause = " OR ".join(conditions)
537 logger.info(f"搜索条件: {where_clause}")
538 logger.info(f"参数列表: {params}")
539
540 if category:
541 where_clause = f"({where_clause}) AND topic_id=%s"
542 params.append(category)
543
544 sql = f"""
545 SELECT p.id, p.title, tp.name as category, p.heat, p.created_at, p.content,
546 GROUP_CONCAT(t.name) as tags
547 FROM posts p
548 LEFT JOIN post_tags pt ON p.id = pt.post_id
549 LEFT JOIN tags t ON pt.tag_id = t.id
550 LEFT JOIN topics tp ON p.topic_id = tp.id
551 WHERE {where_clause}
552 GROUP BY p.id
553 LIMIT 500
554 """
555
556 cursor.execute(sql, params)
557 expanded_results = cursor.fetchall()
558 logger.info(f"数据库返回记录数: {len(expanded_results) if expanded_results else 0}")
559 else:
560 expanded_results = []
561
562 # 如果扩展查询和精确匹配都没有结果,获取全部记录进行相关性计算
563 if not expanded_results and not exact_matches:
564 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"
565 if category:
566 sql += " WHERE p.topic_id=%s"
567 category_params = [category]
568 cursor.execute(sql + " GROUP BY p.id", category_params)
569 else:
570 cursor.execute(sql + " GROUP BY p.id")
571
572 all_results = cursor.fetchall() or [] # 确保返回列表
573 else:
574 if isinstance(exact_matches, tuple):
575 exact_matches = list(exact_matches)
576 if isinstance(expanded_results, tuple):
577 expanded_results = list(expanded_results)
578 all_results = expanded_results + exact_matches
579
580 # 对所有结果使用相关性计算规则
581 scored_results = []
582 for item in all_results:
583 # 计算相关性得分
584 relevance_score = calculate_keyword_relevance(keyword, item)
585
586 # 降低相关性阈值,确保更多结果被保留 (从0.5改为0.1)
587 if relevance_score > 0.1:
588 item['relevance_score'] = relevance_score
589 scored_results.append(item)
590 logger.info(f"匹配项: {item['title']}, 相关性得分: {relevance_score}")
591
592 # 按相关性得分排序
593 scored_results.sort(key=lambda x: x.get('relevance_score', 0), reverse=True)
594
595 # 确保精确匹配的结果置顶
596 if exact_matches:
597 for exact_match in exact_matches:
598 exact_match['relevance_score'] = 20.0 # 超高分确保置顶
599
600 # 移除scored_results中已经存在于exact_matches的项
601 exact_ids = {item['id'] for item in exact_matches}
602 scored_results = [item for item in scored_results if item['id'] not in exact_ids]
603
604 # 合并两个结果集
605 results = exact_matches + scored_results
606 else:
607 results = scored_results
608
609 # 限制返回结果数量
610 results = results[:50]
611
612 except Exception as e:
613 logger.error(f"搜索出错: {e}")
614 import traceback
615 traceback.print_exc()
616 return jsonify({"error": "搜索系统异常,请稍后再试"}), 500
617 finally:
618 conn.close()
619
620 # 第二阶段:根据指定方式排序
621 if results:
622 if sort_by == "similarity" or not sort_by:
623 # 保持按相关性得分排序,已经排好了
624 pass
625 elif sort_by == "downloads":
626 results.sort(key=lambda x: x.get("download_count", 0), reverse=True)
627 elif sort_by == "downloads_asc":
628 results.sort(key=lambda x: x.get("download_count", 0))
629 elif sort_by == "newest":
630 results.sort(key=lambda x: x.get("create_time", ""), reverse=True)
631 elif sort_by == "oldest":
632 results.sort(key=lambda x: x.get("create_time", ""))
633 elif sort_by == "title_asc":
634 results.sort(key=lambda x: x.get("title", ""))
635 elif sort_by == "title_desc":
636 results.sort(key=lambda x: x.get("title", ""), reverse=True)
637
638 # 最终处理:清理不需要返回的字段,并将 datetime 转为字符串
639 for item in results:
640 item.pop("description", None)
641 item.pop("tags", None)
642 item.pop("relevance_score", None)
643 for k, v in item.items():
644 if hasattr(v, 'isoformat'):
645 item[k] = v.isoformat(sep=' ', timespec='seconds')
646
647 return Response(json.dumps({"results": results}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
648
649# 推荐功能的API
650@app.route('/recommend_tags', methods=['POST'])
651def recommend_tags():
652 """
653 推荐功能API
654 请求格式:{
655 "user_id": "user1",
656 "tags": ["标签1", "标签2"] # 可为空
657 }
658 """
659 if request.content_type != 'application/json':
660 return jsonify({"error": "Content-Type must be application/json"}), 415
661
662 data = request.get_json()
663 user_id = data.get("user_id")
664 tags = set(data.get("tags", []))
665
666 # 查询用户已保存的兴趣标签
667 user_tags = set()
668 if user_id:
669 conn = get_db_conn()
670 try:
671 with conn.cursor() as cursor:
672 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,))
673 user_tags = set(row[0] for row in cursor.fetchall())
674 finally:
675 conn.close()
676
677 # 合并前端传递的tags和用户兴趣标签
678 all_tags = list(tags | user_tags)
679
680 if not all_tags:
681 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
682
683 conn = get_db_conn()
684 try:
685 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
686 # 优先用tags字段匹配
687 # 先查找所有tag_id
688 tag_ids = []
689 for tag in all_tags:
690 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
691 row = cursor.fetchone()
692 if row:
693 tag_ids.append(row['id'])
694 if not tag_ids:
695 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
696 tag_placeholders = ','.join(['%s'] * len(tag_ids))
697 sql = f"""
698 SELECT p.id, p.title, tp.name as category, p.heat,
699 GROUP_CONCAT(tg.name) as tags
700 FROM posts p
701 LEFT JOIN post_tags pt ON p.id = pt.post_id
702 LEFT JOIN tags tg ON pt.tag_id = tg.id
703 LEFT JOIN topics tp ON p.topic_id = tp.id
704 WHERE pt.tag_id IN ({tag_placeholders})
705 GROUP BY p.id
706 LIMIT 50
707 """
708 cursor.execute(sql, tuple(tag_ids))
709 results = cursor.fetchall()
710 # 若无结果,回退title/content模糊匹配
711 if not results:
712 or_conditions = []
713 params = []
714 for tag in all_tags:
715 or_conditions.append("p.title LIKE %s OR p.content LIKE %s")
716 params.extend(['%' + tag + '%', '%' + tag + '%'])
717 where_clause = ' OR '.join(or_conditions)
718 sql = f"""
719 SELECT p.id, p.title, tp.name as category, p.heat,
720 GROUP_CONCAT(tg.name) as tags
721 FROM posts p
722 LEFT JOIN post_tags pt ON p.id = pt.post_id
723 LEFT JOIN tags tg ON pt.tag_id = tg.id
724 LEFT JOIN topics tp ON p.topic_id = tp.id
725 WHERE {where_clause}
726 GROUP BY p.id
727 LIMIT 50
728 """
729 cursor.execute(sql, tuple(params))
730 results = cursor.fetchall()
731 finally:
732 conn.close()
733
734 if not results:
735 return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
736
737 return Response(json.dumps({"recommendations": results}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
738
739# 用户兴趣标签管理API(可选)
740@app.route('/tags', methods=['POST', 'GET', 'DELETE'])
741def user_tags():
742 """
743 POST: 添加用户兴趣标签
744 GET: 查询用户兴趣标签
745 DELETE: 删除用户兴趣标签
746 """
747 if request.method == 'POST':
748 if request.content_type != 'application/json':
749 return jsonify({"error": "Content-Type must be application/json"}), 415
750 data = request.get_json()
751 user_id = data.get("user_id")
752 tags = data.get("tags", [])
753
754 if not user_id:
755 return jsonify({"error": "用户ID不能为空"}), 400
756
757 # 确保标签列表格式正确
758 if isinstance(tags, str):
759 tags = [tag.strip() for tag in tags.split(',') if tag.strip()]
760
761 if not tags:
762 return jsonify({"error": "标签不能为空"}), 400
763
764 conn = get_db_conn()
765 try:
766 with conn.cursor() as cursor:
767 # 添加用户标签
768 for tag in tags:
769 # 先查找tag_id
770 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
771 tag_row = cursor.fetchone()
772 if tag_row:
773 tag_id = tag_row[0]
774 cursor.execute("REPLACE INTO user_tags (user_id, tag_id) VALUES (%s, %s)", (user_id, tag_id))
775 conn.commit()
776 # 返回更新后的标签列表
777 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,))
778 updated_tags = [row[0] for row in cursor.fetchall()]
779 finally:
780 conn.close()
781 return Response(json.dumps({"msg": "添加成功", "tags": updated_tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
782 elif request.method == 'DELETE':
783 if request.content_type != 'application/json':
784 return jsonify({"error": "Content-Type must be application/json"}), 415
785 data = request.get_json()
786 user_id = data.get("user_id")
787 tags = data.get("tags", [])
788 if not user_id:
789 return jsonify({"error": "用户ID不能为空"}), 400
790 if not tags:
791 return jsonify({"error": "标签不能为空"}), 400
792
793 conn = get_db_conn()
794 try:
795 with conn.cursor() as cursor:
796 for tag in tags:
797 cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
798 tag_row = cursor.fetchone()
799 if tag_row:
800 tag_id = tag_row[0]
801 cursor.execute("DELETE FROM user_tags WHERE user_id=%s AND tag_id=%s", (user_id, tag_id))
802 conn.commit()
803 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,))
804 remaining_tags = [row[0] for row in cursor.fetchall()]
805 finally:
806 conn.close()
807 return Response(json.dumps({"msg": "删除成功", "tags": remaining_tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
808 else: # GET 请求
809 user_id = request.args.get("user_id")
810 if not user_id:
811 return jsonify({"error": "用户ID不能为空"}), 400
812 conn = get_db_conn()
813 try:
814 with conn.cursor() as cursor:
815 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,))
816 tags = [row[0] for row in cursor.fetchall()]
817 finally:
818 conn.close()
819 return Response(json.dumps({"tags": tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
820
821# 添加/user_tags路由作为/tags的别名
822@app.route('/user_tags', methods=['POST', 'GET', 'DELETE'])
823def user_tags_alias():
824 """
825 /user_tags路由 - 作为/tags路由的别名
826 POST: 添加用户兴趣标签
827 GET: 查询用户兴趣标签
828 DELETE: 删除用户兴趣标签
829 """
830 return user_tags()
831
832# 基于用户的协同过滤推荐API
833@app.route('/user_based_recommend', methods=['POST'])
834def user_based_recommend():
835 """
836 基于用户的协同过滤推荐API
837 请求格式:{
838 "user_id": "user1",
839 "top_n": 5
840 }
841 """
842 if request.content_type != 'application/json':
843 return jsonify({"error": "Content-Type must be application/json"}), 415
844
845 data = request.get_json()
846 user_id = data.get("user_id")
847 top_n = int(data.get("top_n", 5))
848
849 if not user_id:
850 return jsonify({"error": "用户ID不能为空"}), 400
851
852 conn = get_db_conn()
853 try:
854 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
855 # 1. 检查用户是否存在下载记录(收藏或浏览)
856 cursor.execute("""
857 SELECT COUNT(*) as count
858 FROM behaviors
859 WHERE user_id = %s AND type IN ('favorite', 'view')
860 """, (user_id,))
861 result = cursor.fetchone()
862 user_download_count = result['count'] if result else 0
863
864 logger.info(f"用户 {user_id} 下载记录数: {user_download_count}")
865
866 # 如果用户没有足够的行为数据,返回基于热度的推荐
867 if user_download_count < 3:
868 logger.info(f"用户 {user_id} 下载记录不足,返回热门推荐")
869 cursor.execute("""
870 SELECT p.id, p.title, tp.name as category, p.heat
871 FROM posts p
872 LEFT JOIN topics tp ON p.topic_id = tp.id
873 ORDER BY p.heat DESC
874 LIMIT %s
875 """, (top_n,))
876 popular_seeds = cursor.fetchall()
877 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
878
879 # 2. 获取用户已下载(收藏/浏览)的帖子
880 cursor.execute("""
881 SELECT post_id
882 FROM behaviors
883 WHERE user_id = %s AND type IN ('favorite', 'view')
884 """, (user_id,))
885 user_seeds = set(row['post_id'] for row in cursor.fetchall())
886 logger.info(f"用户 {user_id} 已下载种子: {user_seeds}")
887
888 # 3. 获取所有用户-帖子下载(收藏/浏览)矩阵
889 cursor.execute("""
890 SELECT user_id, post_id
891 FROM behaviors
892 WHERE created_at > DATE_SUB(NOW(), INTERVAL 3 MONTH)
893 AND user_id <> %s AND type IN ('favorite', 'view')
894 """, (user_id,))
895 download_records = cursor.fetchall()
896
897 if not download_records:
898 logger.info(f"没有其他用户的下载记录,返回热门推荐")
899 cursor.execute("""
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 ORDER BY p.heat DESC
904 LIMIT %s
905 """, (top_n,))
906 popular_seeds = cursor.fetchall()
907 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
908
909 # 构建用户-物品矩阵
910 user_item_matrix = {}
911 for record in download_records:
912 uid = record['user_id']
913 sid = record['post_id']
914 if uid not in user_item_matrix:
915 user_item_matrix[uid] = set()
916 user_item_matrix[uid].add(sid)
917
918 # 4. 计算用户相似度
919 similar_users = []
920 for other_id, other_seeds in user_item_matrix.items():
921 if other_id == user_id:
922 continue
923 intersection = len(user_seeds.intersection(other_seeds))
924 union = len(user_seeds.union(other_seeds))
925 if union > 0 and intersection > 0:
926 similarity = intersection / union
927 similar_users.append((other_id, similarity, other_seeds))
928 logger.info(f"找到 {len(similar_users)} 个相似用户")
929 similar_users.sort(key=lambda x: x[1], reverse=True)
930 similar_users = similar_users[:5]
931 # 5. 基于相似用户推荐帖子
932 candidate_seeds = {}
933 for similar_user, similarity, seeds in similar_users:
934 logger.info(f"相似用户 {similar_user}, 相似度 {similarity}")
935 for post_id in seeds:
936 if post_id not in user_seeds:
937 if post_id not in candidate_seeds:
938 candidate_seeds[post_id] = 0
939 candidate_seeds[post_id] += similarity
940 if not candidate_seeds:
941 logger.info(f"没有找到候选种子,返回热门推荐")
942 cursor.execute("""
943 SELECT p.id, p.title, tp.name as category, p.heat
944 FROM posts p
945 LEFT JOIN topics tp ON p.topic_id = tp.id
946 ORDER BY p.heat DESC
947 LIMIT %s
948 """, (top_n,))
949 popular_seeds = cursor.fetchall()
950 return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
951 # 6. 获取推荐帖子的详细信息
952 recommended_seeds = sorted(candidate_seeds.items(), key=lambda x: x[1], reverse=True)[:top_n]
953 post_ids = [post_id for post_id, _ in recommended_seeds]
954 format_strings = ','.join(['%s'] * len(post_ids))
955 cursor.execute(f"""
956 SELECT p.id, p.title, tp.name as category, p.heat
957 FROM posts p
958 LEFT JOIN topics tp ON p.topic_id = tp.id
959 WHERE p.id IN ({format_strings})
960 """, tuple(post_ids))
961 result_seeds = cursor.fetchall()
962 seed_score_map = {post_id: score for post_id, score in recommended_seeds}
963 result_seeds.sort(key=lambda x: seed_score_map.get(x['id'], 0), reverse=True)
964 logger.info(f"返回 {len(result_seeds)} 个基于协同过滤的推荐")
965 return Response(json.dumps({"recommendations": result_seeds, "type": "collaborative"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
966 except Exception as e:
967 logger.error(f"推荐系统错误: {e}")
968 import traceback
969 traceback.print_exc()
970 return Response(json.dumps({"error": "推荐系统异常,请稍后再试", "details": str(e)}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
971 finally:
972 conn.close()
973@app.route('/word2vec_status', methods=['GET'])
974def word2vec_status():
975 """
976 检查Word2Vec模型状态
977 返回模型是否加载、词汇量等信息
978 """
979 if not WORD2VEC_ENABLED:
980 return Response(json.dumps({
981 "enabled": False,
982 "message": "Word2Vec功能未启用"
983 }, ensure_ascii=False), mimetype='application/json; charset=utf-8')
984 try:
985 helper = get_word2vec_helper()
986 status = {
987 "enabled": WORD2VEC_ENABLED,
988 "initialized": helper.initialized,
989 "vocab_size": len(helper.model.index_to_key) if helper.model else 0,
990 "vector_size": helper.model.vector_size if helper.model else 0
991 }
992
993 # 测试几个常用词的相似词,展示模型效果
994 test_results = {}
995 test_words = ["电影", "动作", "科幻", "动漫", "游戏"]
996 for word in test_words:
997 similar_words = helper.get_similar_words(word, topn=5)
998 test_results[word] = similar_words
999
1000 status["test_results"] = test_results
1001 return Response(json.dumps(status, ensure_ascii=False), mimetype='application/json; charset=utf-8')
1002 except Exception as e:
1003 return Response(json.dumps({
1004 "enabled": WORD2VEC_ENABLED,
1005 "initialized": False,
1006 "error": str(e)
1007 }, ensure_ascii=False), mimetype='application/json; charset=utf-8')
1008
1009# 添加一个临时诊断端点
1010@app.route('/debug_search', methods=['POST'])
1011def debug_search():
1012 """临时的调试端点,用于检查数据库中的记录"""
1013 if request.content_type != 'application/json':
1014 return jsonify({"error": "Content-Type must be application/json"}), 415
1015
1016 data = request.get_json()
1017 keyword = data.get("keyword", "").strip()
1018
1019 conn = get_db_conn()
1020 try:
1021 with conn.cursor(pymysql.cursors.DictCursor) as cursor:
1022 # 尝试查询包含特定词的所有记录
1023 queries = [
1024 ("标题中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE title LIKE '%{keyword}%' LIMIT 10"),
1025 ("描述中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE description LIKE '%{keyword}%' LIMIT 10"),
1026 ("标签中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE FIND_IN_SET('{keyword}', tags) LIMIT 10"),
1027 ("肖申克的救赎", "SELECT seed_id, title, description, tags FROM pt_seed WHERE title = '肖申克的救赎'")
1028 ]
1029
1030 results = {}
1031 for query_name, query in queries:
1032 cursor.execute(query)
1033 results[query_name] = cursor.fetchall()
1034
1035 return Response(json.dumps(results, ensure_ascii=False), mimetype='application/json; charset=utf-8')
1036 finally:
1037 conn.close()
1038
1039"""
1040接口本地测试方法(可直接运行main_online.py后用curl或Postman测试):
1041
10421. 搜索接口
1043curl -X POST http://127.0.0.1:5000/search -H "Content-Type: application/json" -d '{"keyword":"电影","sort_by":"downloads"}'
1044
10452. 标签推荐接口
1046curl -X POST http://127.0.0.1:5000/recommend_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
1047
10483. 用户兴趣标签管理(添加标签)
1049curl -X POST http://127.0.0.1:5000/user_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
1050
10514. 用户兴趣标签管理(查询标签)
1052curl "http://127.0.0.1:5000/user_tags?user_id=1"
1053
10545. 用户兴趣标签管理(删除标签)
1055curl -X DELETE http://127.0.0.1:5000/user_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
1056
10576. 协同过滤推荐
1058curl -X POST http://127.0.0.1:5000/user_based_recommend -H "Content-Type: application/json" -d '{"user_id":"user1","top_n":3}'
1059
10607. Word2Vec状态检查
1061curl "http://127.0.0.1:5000/word2vec_status"
1062
10638. 调试接口(临时)
1064curl -X POST http://127.0.0.1:5000/debug_search -H "Content-Type: application/json" -d '{"keyword":"电影"}'
1065
1066所有接口均可用Postman按上述参数测试。
1067"""
1068
1069if __name__ == "__main__":
1070 try:
1071 logger.info("搜索推荐服务启动中...")
TRM-codingf55d2372025-06-20 16:22:37 +08001072 app.run(host="0.0.0.0", port=5717)
95630366980c1f272025-06-20 14:08:54 +08001073 except Exception as e:
1074 logger.error(f"启动异常: {e}")
1075 import traceback
1076 traceback.print_exc()