test_evaluation_v3.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. """
  2. 测试评估V3模块
  3. 从现有run_context.json读取帖子,使用V3评估模块重新评估,生成统计报告
  4. """
  5. import asyncio
  6. import json
  7. import sys
  8. from pathlib import Path
  9. from datetime import datetime
  10. from collections import defaultdict
  11. # 导入必要的模块
  12. from knowledge_search_traverse import Post
  13. from post_evaluator_v3 import evaluate_post_v3, apply_evaluation_v3_to_post
  14. async def test_evaluation_v3(run_context_path: str, max_posts: int = 10):
  15. """
  16. 测试V3评估模块
  17. Args:
  18. run_context_path: run_context.json路径
  19. max_posts: 最多评估的帖子数量(用于快速测试)
  20. """
  21. print(f"\n{'='*80}")
  22. print(f"📊 评估V3测试 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  23. print(f"{'='*80}\n")
  24. # 读取run_context.json
  25. print(f"📂 读取: {run_context_path}")
  26. with open(run_context_path, 'r', encoding='utf-8') as f:
  27. run_context = json.load(f)
  28. # 提取原始query
  29. original_query = run_context.get('o', '')
  30. print(f"🔍 原始Query: {original_query}\n")
  31. # 提取所有帖子 (从rounds -> search_results -> post_list)
  32. post_data_list = []
  33. rounds = run_context.get('rounds', [])
  34. for round_idx, round_data in enumerate(rounds):
  35. search_results = round_data.get('search_results', [])
  36. for search_idx, search in enumerate(search_results):
  37. post_list = search.get('post_list', [])
  38. for post_idx, post_data in enumerate(post_list):
  39. # 生成唯一ID
  40. post_id = f"r{round_idx}_s{search_idx}_p{post_idx}"
  41. post_data_list.append((round_idx, search_idx, post_id, post_data))
  42. total_posts = len(post_data_list)
  43. print(f"📝 找到 {total_posts} 个帖子 (来自 {len(rounds)} 轮)")
  44. # 限制评估数量(快速测试)
  45. if max_posts and max_posts < total_posts:
  46. post_data_list = post_data_list[:max_posts]
  47. print(f"⚡ 快速测试模式: 仅评估前 {max_posts} 个帖子\n")
  48. else:
  49. print()
  50. # 将post_data转换为Post对象
  51. posts = []
  52. for round_idx, search_idx, post_id, post_data in post_data_list:
  53. post = Post(
  54. note_id=post_data.get('note_id', post_id),
  55. title=post_data.get('title', ''),
  56. body_text=post_data.get('body_text', ''),
  57. images=post_data.get('images', []),
  58. type=post_data.get('type', 'normal')
  59. )
  60. posts.append((round_idx, search_idx, post_id, post))
  61. # 批量评估
  62. print(f"🚀 开始并行评估 (最多{len(posts)}个任务,并发限制: 5)...\n")
  63. semaphore = asyncio.Semaphore(5)
  64. tasks = []
  65. # 1. 创建所有任务
  66. for round_idx, search_idx, post_id, post in posts:
  67. task = evaluate_post_v3(post, original_query, semaphore)
  68. tasks.append((round_idx, search_idx, post_id, post, task))
  69. # 2. 并行执行所有任务
  70. task_coroutines = [task for _, _, _, _, task in tasks]
  71. all_eval_results = await asyncio.gather(*task_coroutines)
  72. # 3. 处理结果
  73. results = []
  74. detailed_reports = [] # 收集详细评估报告
  75. print(f"📊 处理评估结果...\n")
  76. for i, ((round_idx, search_idx, post_id, post, _), eval_result) in enumerate(zip(tasks, all_eval_results), 1):
  77. knowledge_eval, content_eval, purpose_eval, category_eval, final_score, match_level = eval_result
  78. print(f" [{i}/{len(tasks)}] {post.note_id} - {post.title[:40]}", end="")
  79. if knowledge_eval:
  80. if final_score is not None:
  81. print(f" → {match_level} ({final_score:.1f}分)")
  82. elif content_eval and not content_eval.is_content_knowledge:
  83. print(f" → 非内容知识")
  84. elif knowledge_eval and not knowledge_eval.is_knowledge:
  85. print(f" → 非知识")
  86. else:
  87. print(f" → 评估未完成")
  88. # 打印详细判断原因
  89. print(f" 📝 知识评估: {knowledge_eval.conclusion if knowledge_eval.conclusion else '无'}")
  90. if content_eval and content_eval.is_content_knowledge:
  91. print(f" 📚 内容知识: {content_eval.summary[:80] if content_eval.summary else '无'}...")
  92. if purpose_eval:
  93. print(f" 🎯 目的匹配: {purpose_eval.core_basis[:80] if purpose_eval.core_basis else '无'}...")
  94. if category_eval:
  95. print(f" 🏷️ 品类匹配: {category_eval.core_basis[:80] if category_eval.core_basis else '无'}...")
  96. print()
  97. # 收集详细报告
  98. detailed_report = {
  99. 'post_index': i,
  100. 'note_id': post.note_id,
  101. 'title': post.title,
  102. 'final_score': final_score,
  103. 'match_level': match_level,
  104. 'is_knowledge': knowledge_eval.is_knowledge if knowledge_eval else None,
  105. 'is_content_knowledge': content_eval.is_content_knowledge if content_eval else None,
  106. 'knowledge_score': content_eval.final_score if content_eval else None,
  107. 'evaluations': {
  108. 'knowledge': {
  109. 'conclusion': knowledge_eval.conclusion if knowledge_eval else None,
  110. 'core_evidence': knowledge_eval.core_evidence if knowledge_eval and hasattr(knowledge_eval, 'core_evidence') else None,
  111. 'issues': knowledge_eval.issues if knowledge_eval and hasattr(knowledge_eval, 'issues') else None
  112. },
  113. 'content_knowledge': {
  114. 'summary': content_eval.summary if content_eval else None,
  115. 'final_score': content_eval.final_score if content_eval else None,
  116. 'level': content_eval.level if content_eval else None
  117. } if content_eval and content_eval.is_content_knowledge else None,
  118. 'purpose': {
  119. 'score': purpose_eval.purpose_score if purpose_eval else None,
  120. 'core_motivation': purpose_eval.core_motivation if purpose_eval else None,
  121. 'core_basis': purpose_eval.core_basis if purpose_eval else None,
  122. 'match_level': purpose_eval.match_level if purpose_eval else None
  123. } if purpose_eval else None,
  124. 'category': {
  125. 'score': category_eval.category_score if category_eval else None,
  126. 'core_basis': category_eval.core_basis if category_eval else None,
  127. 'match_level': category_eval.match_level if category_eval else None
  128. } if category_eval else None
  129. }
  130. }
  131. detailed_reports.append(detailed_report)
  132. # 应用评估结果
  133. apply_evaluation_v3_to_post(
  134. post,
  135. knowledge_eval,
  136. content_eval,
  137. purpose_eval,
  138. category_eval,
  139. final_score,
  140. match_level
  141. )
  142. results.append((round_idx, search_idx, post_id, post))
  143. else:
  144. print(f" → ❌ 评估失败\n")
  145. print(f"\n✅ 评估完成: {len(results)}/{len(posts)} 成功\n")
  146. # 更新run_context.json中的帖子数据
  147. print("💾 更新 run_context.json...")
  148. for round_idx, search_idx, post_id, post in results:
  149. # 定位到对应的post_list
  150. if round_idx < len(rounds):
  151. search_results = rounds[round_idx].get('search_results', [])
  152. if search_idx < len(search_results):
  153. post_list = search_results[search_idx].get('post_list', [])
  154. # 找到对应的帖子并更新
  155. for p in post_list:
  156. if p.get('note_id') == post.note_id:
  157. # 更新V3顶层字段
  158. p['is_knowledge'] = post.is_knowledge
  159. p['is_content_knowledge'] = post.is_content_knowledge
  160. p['knowledge_score'] = post.knowledge_score
  161. p['purpose_score'] = post.purpose_score
  162. p['category_score'] = post.category_score
  163. p['final_score'] = post.final_score
  164. p['match_level'] = post.match_level
  165. p['evaluation_time'] = post.evaluation_time
  166. p['evaluator_version'] = post.evaluator_version
  167. # 更新V3嵌套字段
  168. p['knowledge_evaluation'] = post.knowledge_evaluation
  169. p['content_knowledge_evaluation'] = post.content_knowledge_evaluation
  170. p['purpose_evaluation'] = post.purpose_evaluation
  171. p['category_evaluation'] = post.category_evaluation
  172. break
  173. # 保存更新后的run_context.json
  174. output_path = run_context_path.replace('.json', '_v3.json')
  175. with open(output_path, 'w', encoding='utf-8') as f:
  176. json.dump(run_context, f, ensure_ascii=False, indent=2)
  177. print(f"✅ 已保存: {output_path}")
  178. # 保存详细评估报告
  179. report_path = run_context_path.replace('.json', '_evaluation_report.json')
  180. evaluation_report = {
  181. 'metadata': {
  182. 'original_query': original_query,
  183. 'total_posts': len(results),
  184. 'evaluation_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  185. 'evaluator_version': 'v3.0'
  186. },
  187. 'detailed_reports': detailed_reports
  188. }
  189. with open(report_path, 'w', encoding='utf-8') as f:
  190. json.dump(evaluation_report, f, ensure_ascii=False, indent=2)
  191. print(f"📄 已保存详细评估报告: {report_path}\n")
  192. # 生成统计报告
  193. print(f"\n{'='*80}")
  194. print("📊 统计报告")
  195. print(f"{'='*80}\n")
  196. # Prompt1: 是否是知识
  197. is_knowledge_counts = defaultdict(int)
  198. for _, _, _, post in results:
  199. if post.is_knowledge:
  200. is_knowledge_counts['是知识'] += 1
  201. else:
  202. is_knowledge_counts['非知识'] += 1
  203. total = len(results)
  204. print("🔍 Prompt1 - 是否是知识:")
  205. print(f" 是知识: {is_knowledge_counts['是知识']:3d} / {total} ({is_knowledge_counts['是知识']/total*100:.1f}%)")
  206. print(f" 非知识: {is_knowledge_counts['非知识']:3d} / {total} ({is_knowledge_counts['非知识']/total*100:.1f}%)")
  207. print()
  208. # Prompt2: 是否是内容知识
  209. is_content_knowledge_counts = defaultdict(int)
  210. knowledge_scores = []
  211. for _, _, _, post in results:
  212. if post.is_content_knowledge is not None:
  213. if post.is_content_knowledge:
  214. is_content_knowledge_counts['是内容知识'] += 1
  215. else:
  216. is_content_knowledge_counts['非内容知识'] += 1
  217. if post.knowledge_score is not None:
  218. knowledge_scores.append(post.knowledge_score)
  219. if is_content_knowledge_counts:
  220. content_total = sum(is_content_knowledge_counts.values())
  221. print("📚 Prompt2 - 是否是内容知识:")
  222. print(f" 是内容知识: {is_content_knowledge_counts['是内容知识']:3d} / {content_total} ({is_content_knowledge_counts['是内容知识']/content_total*100:.1f}%)")
  223. if is_content_knowledge_counts['非内容知识'] > 0:
  224. print(f" 非内容知识: {is_content_knowledge_counts['非内容知识']:3d} / {content_total} ({is_content_knowledge_counts['非内容知识']/content_total*100:.1f}%)")
  225. print()
  226. if knowledge_scores:
  227. avg_score = sum(knowledge_scores) / len(knowledge_scores)
  228. print(f" 知识平均得分: {avg_score:.1f}分")
  229. print(f" 知识最高得分: {max(knowledge_scores):.0f}分")
  230. print(f" 知识最低得分: {min(knowledge_scores):.0f}分")
  231. print()
  232. # Prompt3 & Prompt4: 目的性和品类匹配
  233. purpose_scores = []
  234. category_scores = []
  235. final_scores = []
  236. match_level_counts = defaultdict(int)
  237. for _, _, _, post in results:
  238. if post.purpose_score is not None:
  239. purpose_scores.append(post.purpose_score)
  240. if post.category_score is not None:
  241. category_scores.append(post.category_score)
  242. if post.final_score is not None:
  243. final_scores.append(post.final_score)
  244. if post.match_level:
  245. match_level_counts[post.match_level] += 1
  246. if purpose_scores:
  247. avg_purpose = sum(purpose_scores) / len(purpose_scores)
  248. print("🎯 Prompt3 - 目的性匹配:")
  249. print(f" 平均得分: {avg_purpose:.1f}分")
  250. print(f" 最高得分: {max(purpose_scores):.0f}分")
  251. print(f" 最低得分: {min(purpose_scores):.0f}分")
  252. print()
  253. if category_scores:
  254. avg_category = sum(category_scores) / len(category_scores)
  255. print("🏷️ Prompt4 - 品类匹配:")
  256. print(f" 平均得分: {avg_category:.1f}分")
  257. print(f" 最高得分: {max(category_scores):.0f}分")
  258. print(f" 最低得分: {min(category_scores):.0f}分")
  259. print()
  260. if final_scores:
  261. avg_final = sum(final_scores) / len(final_scores)
  262. print("🔥 综合得分 (目的性70% + 品类30%):")
  263. print(f" 平均得分: {avg_final:.2f}分")
  264. print(f" 最高得分: {max(final_scores):.2f}分")
  265. print(f" 最低得分: {min(final_scores):.2f}分")
  266. print()
  267. if match_level_counts:
  268. print("📊 匹配等级分布:")
  269. for level in ['高度匹配', '基本匹配', '部分匹配', '弱匹配', '不匹配']:
  270. count = match_level_counts.get(level, 0)
  271. if count > 0:
  272. bar = '█' * int(count / total * 50)
  273. print(f" {level:8s}: {count:3d} / {total} ({count/total*100:.1f}%) {bar}")
  274. print()
  275. # 综合分析
  276. print("🌟 高质量内容统计:")
  277. # 是知识 + 是内容知识
  278. is_quality_knowledge = sum(
  279. 1 for _, _, _, post in results
  280. if post.is_knowledge and post.is_content_knowledge
  281. )
  282. print(f" 知识内容: {is_quality_knowledge} / {total} ({is_quality_knowledge/total*100:.1f}%)")
  283. # 是知识 + 是内容知识 + 高度匹配
  284. high_match = sum(
  285. 1 for _, _, _, post in results
  286. if post.is_knowledge and post.is_content_knowledge and post.match_level == '高度匹配'
  287. )
  288. print(f" 高度匹配: {high_match} / {total} ({high_match/total*100:.1f}%)")
  289. # 是知识 + 是内容知识 + 综合得分>=70
  290. high_score = sum(
  291. 1 for _, _, _, post in results
  292. if post.is_knowledge and post.is_content_knowledge and post.final_score and post.final_score >= 70
  293. )
  294. print(f" 得分≥70: {high_score} / {total} ({high_score/total*100:.1f}%)")
  295. print()
  296. print(f"{'='*80}\n")
  297. return results
  298. if __name__ == "__main__":
  299. if len(sys.argv) < 2:
  300. print("用法: python3 test_evaluation_v3.py <run_context.json路径> [最大评估数量]")
  301. print()
  302. print("示例:")
  303. print(" python3 test_evaluation_v3.py input/test_case/output/knowledge_search_traverse/20251112/173512_dc/run_context.json")
  304. print(" python3 test_evaluation_v3.py input/test_case/output/knowledge_search_traverse/20251112/173512_dc/run_context.json 20")
  305. sys.exit(1)
  306. run_context_path = sys.argv[1]
  307. max_posts = int(sys.argv[2]) if len(sys.argv) > 2 else None
  308. asyncio.run(test_evaluation_v3(run_context_path, max_posts))