test_evaluation_v3.py 16 KB

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