match_inspiration_features.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 灵感点特征匹配脚本
  5. 从解构任务列表中提取灵感点的特征,与人设灵感特征进行匹配,
  6. 使用 relation_analyzer 模块分析特征之间的语义关系。
  7. """
  8. import json
  9. import asyncio
  10. from pathlib import Path
  11. from typing import Dict, List
  12. import sys
  13. from tqdm import tqdm
  14. # 添加项目根目录到路径
  15. project_root = Path(__file__).parent.parent.parent
  16. sys.path.insert(0, str(project_root))
  17. from lib.hybrid_similarity import compare_phrases_cartesian
  18. from script.data_processing.path_config import PathConfig
  19. # 全局进度条
  20. progress_bar = None
  21. async def process_single_point(
  22. point: Dict,
  23. point_type: str,
  24. persona_features: List[Dict],
  25. category_mapping: Dict = None,
  26. model_name: str = None
  27. ) -> Dict:
  28. """
  29. 处理单个点 - 使用笛卡尔积批量计算(优化版)
  30. Args:
  31. point: 点数据(灵感点/关键点/目的点)
  32. point_type: 点类型("灵感点"/"关键点"/"目的点")
  33. persona_features: 人设特征列表
  34. category_mapping: 特征分类映射字典
  35. model_name: 使用的模型名称
  36. Returns:
  37. 包含匹配人设结果的点数据
  38. """
  39. global progress_bar
  40. point_name = point.get("名称", "")
  41. # 如果没有人设特征,直接返回
  42. if not persona_features:
  43. result = point.copy()
  44. result["匹配人设结果"] = []
  45. return result
  46. # 提取人设名称列表
  47. persona_names = [pf["特征名称"] for pf in persona_features]
  48. # 定义进度回调函数
  49. def on_llm_progress(count: int):
  50. """LLM完成一个任务时的回调"""
  51. if progress_bar:
  52. progress_bar.update(count)
  53. # 核心优化:使用混合模型笛卡尔积一次计算1×N(点名称 vs 所有人设)
  54. similarity_results = await compare_phrases_cartesian(
  55. [point_name], # 1个点名称
  56. persona_names, # N个人设
  57. max_concurrent=100, # LLM最大并发数(全局共享)
  58. progress_callback=on_llm_progress # 传递进度回调
  59. )
  60. # similarity_results[0][j] = {"相似度": float, "说明": str}
  61. # 构建匹配结果
  62. match_results = []
  63. for j, persona_feature in enumerate(persona_features):
  64. persona_name = persona_feature["特征名称"]
  65. persona_level = persona_feature["人设特征层级"]
  66. # 直接使用模块返回的完整结果
  67. similarity_result = similarity_results[0][j]
  68. # 判断特征类型和分类
  69. feature_type = "分类" # 默认为分类
  70. categories = []
  71. if category_mapping:
  72. # 先在标签特征中查找
  73. is_tag_feature = False
  74. for ft in ["灵感点", "关键点", "目的点"]:
  75. if ft in category_mapping:
  76. type_mapping = category_mapping[ft]
  77. if persona_name in type_mapping:
  78. feature_type = "标签"
  79. categories = type_mapping[persona_name].get("所属分类", [])
  80. is_tag_feature = True
  81. break
  82. # 如果不是标签特征,检查是否是分类特征
  83. if not is_tag_feature:
  84. all_categories = set()
  85. for ft in ["灵感点", "关键点", "目的点"]:
  86. if ft in category_mapping:
  87. for _fname, fdata in category_mapping[ft].items():
  88. cats = fdata.get("所属分类", [])
  89. all_categories.update(cats)
  90. if persona_name in all_categories:
  91. feature_type = "分类"
  92. categories = []
  93. # 去重分类
  94. unique_categories = list(dict.fromkeys(categories))
  95. match_result = {
  96. "人设特征名称": persona_name,
  97. "人设特征层级": persona_level,
  98. "特征类型": feature_type,
  99. "特征分类": unique_categories,
  100. "相似度": similarity_result.get("相似度", 0),
  101. "说明": similarity_result.get("说明", "")
  102. }
  103. match_results.append(match_result)
  104. # 按相似度降序排列
  105. match_results.sort(key=lambda x: x.get("相似度", 0), reverse=True)
  106. result = point.copy()
  107. result["匹配人设结果"] = match_results
  108. return result
  109. async def process_single_task(
  110. task: Dict,
  111. task_index: int,
  112. total_tasks: int,
  113. all_persona_features: List[Dict],
  114. category_mapping: Dict = None,
  115. model_name: str = None
  116. ) -> Dict:
  117. """
  118. 处理单个任务
  119. Args:
  120. task: 任务数据
  121. task_index: 任务索引(从1开始)
  122. total_tasks: 总任务数
  123. all_persona_features: 所有人设特征列表(包含三种层级)
  124. category_mapping: 特征分类映射字典
  125. model_name: 使用的模型名称
  126. Returns:
  127. 包含解构结果的任务(简化结构)
  128. """
  129. global progress_bar
  130. post_id = task.get("帖子id", "")
  131. # 获取 what 解构结果
  132. what_result = task.get("what解构结果", {})
  133. # 计算当前帖子的总匹配任务数(每个点匹配所有人设特征)
  134. current_task_match_count = 0
  135. for point_type in ["灵感点", "关键点", "目的点"]:
  136. point_list = what_result.get(f"{point_type}列表", [])
  137. current_task_match_count += len(point_list) * len(all_persona_features)
  138. # 创建当前帖子的进度条
  139. progress_bar = tqdm(
  140. total=current_task_match_count,
  141. desc=f"[{task_index}/{total_tasks}] {post_id}",
  142. unit="匹配",
  143. ncols=100
  144. )
  145. # 构建解构结果(简化结构:直接在点上添加匹配人设结果)
  146. result_data = {}
  147. # 串行处理灵感点、关键点和目的点
  148. for point_type in ["灵感点", "关键点", "目的点"]:
  149. point_list_key = f"{point_type}列表"
  150. point_list = what_result.get(point_list_key, [])
  151. if point_list:
  152. updated_point_list = []
  153. # 串行处理每个点
  154. for point in point_list:
  155. result = await process_single_point(
  156. point=point,
  157. point_type=point_type,
  158. persona_features=all_persona_features,
  159. category_mapping=category_mapping,
  160. model_name=model_name
  161. )
  162. updated_point_list.append(result)
  163. result_data[point_list_key] = updated_point_list
  164. # 关闭当前帖子的进度条
  165. if progress_bar:
  166. progress_bar.close()
  167. # 构建简化的输出结构
  168. output = {
  169. "帖子id": task.get("帖子id", ""),
  170. "帖子详情": task.get("帖子详情", {}),
  171. "解构结果": result_data
  172. }
  173. return output
  174. async def process_task_list(
  175. task_list: List[Dict],
  176. persona_features_dict: Dict,
  177. category_mapping: Dict = None,
  178. model_name: str = None,
  179. output_dir: Path = None
  180. ) -> List[Dict]:
  181. """
  182. 处理整个解构任务列表(串行执行,每个帖子处理完立即保存)
  183. Args:
  184. task_list: 解构任务列表
  185. persona_features_dict: 人设特征字典(包含灵感点、目的点、关键点)
  186. category_mapping: 特征分类映射字典
  187. model_name: 使用的模型名称
  188. output_dir: 输出目录(如果提供,每个帖子处理完立即保存)
  189. Returns:
  190. 包含 how 解构结果的任务列表
  191. """
  192. # 合并三种人设特征(灵感点、关键点、目的点)
  193. all_features = []
  194. for feature_type in ["灵感点", "关键点", "目的点"]:
  195. # 获取该类型的标签特征
  196. type_features = persona_features_dict.get(feature_type, [])
  197. # 为每个特征添加层级信息
  198. for feature in type_features:
  199. feature_with_level = feature.copy()
  200. feature_with_level["人设特征层级"] = feature_type
  201. all_features.append(feature_with_level)
  202. print(f"人设{feature_type}标签特征数量: {len(type_features)}")
  203. # 从分类映射中提取该类型的分类特征
  204. if category_mapping and feature_type in category_mapping:
  205. type_categories = set()
  206. for _, feature_data in category_mapping[feature_type].items():
  207. categories = feature_data.get("所属分类", [])
  208. type_categories.update(categories)
  209. # 转换为特征格式并添加层级信息
  210. for cat in sorted(type_categories):
  211. all_features.append({
  212. "特征名称": cat,
  213. "人设特征层级": feature_type
  214. })
  215. print(f"人设{feature_type}分类特征数量: {len(type_categories)}")
  216. print(f"总特征数量(三种类型的标签+分类): {len(all_features)}")
  217. # 计算总匹配任务数(灵感点、关键点和目的点)
  218. total_match_count = 0
  219. for task in task_list:
  220. what_result = task.get("what解构结果", {})
  221. for point_type in ["灵感点", "关键点", "目的点"]:
  222. point_list = what_result.get(f"{point_type}列表", [])
  223. for point in point_list:
  224. # 新结构:点本身就是一个特征;旧结构:使用特征列表
  225. feature_list = point.get("特征列表", None)
  226. feature_count = len(feature_list) if feature_list else 1
  227. total_match_count += feature_count * len(all_features)
  228. print(f"处理灵感点、关键点和目的点特征")
  229. print(f"总匹配任务数: {total_match_count:,}")
  230. print()
  231. # 串行处理所有任务(一个接一个,每个处理完立即保存)
  232. updated_task_list = []
  233. for i, task in enumerate(task_list, 1):
  234. updated_task = await process_single_task(
  235. task=task,
  236. task_index=i,
  237. total_tasks=len(task_list),
  238. all_persona_features=all_features,
  239. category_mapping=category_mapping,
  240. model_name=model_name
  241. )
  242. updated_task_list.append(updated_task)
  243. # 立即保存当前帖子的结果
  244. if output_dir:
  245. post_id = updated_task.get("帖子id", "unknown")
  246. output_file = output_dir / f"{post_id}_how.json"
  247. with open(output_file, "w", encoding="utf-8") as f:
  248. json.dump(updated_task, f, ensure_ascii=False, indent=4)
  249. print(f" ✓ 已保存: {output_file.name}")
  250. return updated_task_list
  251. async def main():
  252. """主函数"""
  253. # 使用路径配置
  254. config = PathConfig()
  255. # 确保输出目录存在
  256. config.ensure_dirs()
  257. # 获取路径
  258. task_list_file = config.task_list_file
  259. persona_features_file = config.feature_source_mapping_file
  260. category_mapping_file = config.feature_category_mapping_file
  261. output_dir = config.how_results_dir
  262. print(f"账号: {config.account_name}")
  263. print(f"任务列表文件: {task_list_file}")
  264. print(f"人设特征文件: {persona_features_file}")
  265. print(f"分类映射文件: {category_mapping_file}")
  266. print(f"输出目录: {output_dir}")
  267. print()
  268. print(f"读取解构任务列表: {task_list_file}")
  269. with open(task_list_file, "r", encoding="utf-8") as f:
  270. task_list_data = json.load(f)
  271. print(f"读取人设特征: {persona_features_file}")
  272. with open(persona_features_file, "r", encoding="utf-8") as f:
  273. persona_features_data = json.load(f)
  274. print(f"读取特征分类映射: {category_mapping_file}")
  275. with open(category_mapping_file, "r", encoding="utf-8") as f:
  276. category_mapping = json.load(f)
  277. # 获取任务列表(支持列表格式和字典格式)
  278. if isinstance(task_list_data, list):
  279. task_list = task_list_data
  280. else:
  281. task_list = task_list_data.get("解构任务列表", [])
  282. print(f"总任务数: {len(task_list)}")
  283. # 处理任务列表(每个帖子处理完立即保存)
  284. updated_task_list = await process_task_list(
  285. task_list=task_list,
  286. persona_features_dict=persona_features_data,
  287. category_mapping=category_mapping,
  288. model_name=None, # 使用默认模型
  289. output_dir=output_dir # 传递输出目录,启用即时保存
  290. )
  291. print("\n完成!")
  292. # 打印统计信息
  293. total_inspiration_points = 0
  294. total_key_points = 0
  295. total_purpose_points = 0
  296. total_matches = 0
  297. for task in updated_task_list:
  298. result = task.get("解构结果", {})
  299. # 统计灵感点
  300. inspiration_list = result.get("灵感点列表", [])
  301. total_inspiration_points += len(inspiration_list)
  302. for point in inspiration_list:
  303. total_matches += len(point.get("匹配人设结果", []))
  304. # 统计关键点
  305. key_list = result.get("关键点列表", [])
  306. total_key_points += len(key_list)
  307. for point in key_list:
  308. total_matches += len(point.get("匹配人设结果", []))
  309. # 统计目的点
  310. purpose_list = result.get("目的点列表", [])
  311. total_purpose_points += len(purpose_list)
  312. for point in purpose_list:
  313. total_matches += len(point.get("匹配人设结果", []))
  314. print(f"\n统计:")
  315. print(f" 处理的帖子数: {len(updated_task_list)}")
  316. print(f" 处理的灵感点数: {total_inspiration_points}")
  317. print(f" 处理的关键点数: {total_key_points}")
  318. print(f" 处理的目的点数: {total_purpose_points}")
  319. print(f" 总匹配数: {total_matches}")
  320. if __name__ == "__main__":
  321. asyncio.run(main())