match_inspiration_features.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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 datetime import datetime
  14. # 添加项目根目录到路径
  15. project_root = Path(__file__).parent.parent.parent
  16. sys.path.insert(0, str(project_root))
  17. from lib.semantic_similarity import compare_phrases
  18. # 全局并发限制
  19. MAX_CONCURRENT_REQUESTS = 100
  20. semaphore = None
  21. # 进度跟踪
  22. class ProgressTracker:
  23. """进度跟踪器"""
  24. def __init__(self, total: int):
  25. self.total = total
  26. self.completed = 0
  27. self.start_time = datetime.now()
  28. self.last_update_time = datetime.now()
  29. self.last_completed = 0
  30. def update(self, count: int = 1):
  31. """更新进度"""
  32. self.completed += count
  33. current_time = datetime.now()
  34. # 每秒最多更新一次,或者达到总数时更新
  35. if (current_time - self.last_update_time).total_seconds() >= 1.0 or self.completed >= self.total:
  36. self.display()
  37. self.last_update_time = current_time
  38. self.last_completed = self.completed
  39. def display(self):
  40. """显示进度"""
  41. if self.total == 0:
  42. return
  43. percentage = (self.completed / self.total) * 100
  44. elapsed = (datetime.now() - self.start_time).total_seconds()
  45. # 计算速度和预估剩余时间
  46. if elapsed > 0:
  47. speed = self.completed / elapsed
  48. if speed > 0:
  49. remaining = (self.total - self.completed) / speed
  50. eta_str = f", 预计剩余: {int(remaining)}秒"
  51. else:
  52. eta_str = ""
  53. else:
  54. eta_str = ""
  55. bar_length = 40
  56. filled_length = int(bar_length * self.completed / self.total)
  57. bar = '█' * filled_length + '░' * (bar_length - filled_length)
  58. print(f"\r 进度: [{bar}] {self.completed}/{self.total} ({percentage:.1f}%){eta_str}", end='', flush=True)
  59. # 完成时换行
  60. if self.completed >= self.total:
  61. print()
  62. # 全局进度跟踪器
  63. progress_tracker = None
  64. def get_semaphore():
  65. """获取全局信号量"""
  66. global semaphore
  67. if semaphore is None:
  68. semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
  69. return semaphore
  70. async def match_single_pair(
  71. feature_name: str,
  72. persona_name: str,
  73. persona_feature_level: str,
  74. category_mapping: Dict = None,
  75. model_name: str = None
  76. ) -> Dict:
  77. """
  78. 匹配单个特征对(带并发限制)
  79. Args:
  80. feature_name: 要匹配的特征名称
  81. persona_name: 人设特征名称
  82. persona_feature_level: 人设特征层级(灵感点/关键点/目的点)
  83. category_mapping: 特征分类映射字典
  84. model_name: 使用的模型名称
  85. Returns:
  86. 单个匹配结果,格式:
  87. {
  88. "人设特征名称": "xxx",
  89. "人设特征层级": "灵感点",
  90. "特征类型": "标签",
  91. "特征分类": ["分类1", "分类2"],
  92. "匹配结果": {
  93. "相似度": 0.75,
  94. "说明": "..."
  95. }
  96. }
  97. """
  98. global progress_tracker
  99. sem = get_semaphore()
  100. async with sem:
  101. similarity_result = await compare_phrases(
  102. phrase_a=feature_name,
  103. phrase_b=persona_name,
  104. )
  105. # 更新进度
  106. if progress_tracker:
  107. progress_tracker.update(1)
  108. # 判断该特征是标签还是分类
  109. feature_type = "分类" # 默认为分类
  110. categories = []
  111. if category_mapping:
  112. # 先在标签特征中查找(灵感点、关键点、目的点)
  113. is_tag_feature = False
  114. for ft in ["灵感点", "关键点", "目的点"]:
  115. if ft in category_mapping:
  116. type_mapping = category_mapping[ft]
  117. if persona_name in type_mapping:
  118. # 找到了,说明是标签特征
  119. feature_type = "标签"
  120. categories = type_mapping[persona_name].get("所属分类", [])
  121. is_tag_feature = True
  122. break
  123. # 如果不是标签特征,检查是否是分类特征
  124. if not is_tag_feature:
  125. # 收集所有分类
  126. all_categories = set()
  127. for ft in ["灵感点", "关键点", "目的点"]:
  128. if ft in category_mapping:
  129. for fname, fdata in category_mapping[ft].items():
  130. cats = fdata.get("所属分类", [])
  131. all_categories.update(cats)
  132. # 如果当前特征名在分类列表中,则是分类特征
  133. if persona_name in all_categories:
  134. feature_type = "分类"
  135. categories = [] # 分类特征本身没有所属分类
  136. # 去重分类
  137. unique_categories = list(dict.fromkeys(categories))
  138. return {
  139. "人设特征名称": persona_name,
  140. "人设特征层级": persona_feature_level,
  141. "特征类型": feature_type,
  142. "特征分类": unique_categories,
  143. "匹配结果": similarity_result
  144. }
  145. async def match_feature_with_persona(
  146. feature_name: str,
  147. persona_features: List[Dict],
  148. category_mapping: Dict = None,
  149. model_name: str = None
  150. ) -> List[Dict]:
  151. """
  152. 将一个特征与人设特征列表进行匹配(并发执行)
  153. Args:
  154. feature_name: 要匹配的特征名称
  155. persona_features: 人设特征列表(包含"特征名称"和"人设特征层级")
  156. category_mapping: 特征分类映射字典
  157. model_name: 使用的模型名称
  158. Returns:
  159. 匹配结果列表
  160. """
  161. # 创建所有匹配任务
  162. tasks = [
  163. match_single_pair(
  164. feature_name,
  165. persona_feature["特征名称"],
  166. persona_feature["人设特征层级"],
  167. category_mapping,
  168. model_name
  169. )
  170. for persona_feature in persona_features
  171. ]
  172. # 并发执行所有匹配
  173. match_results = await asyncio.gather(*tasks)
  174. return list(match_results)
  175. async def match_single_feature(
  176. feature_item: Dict,
  177. persona_features: List[Dict],
  178. category_mapping: Dict = None,
  179. model_name: str = None
  180. ) -> Dict:
  181. """
  182. 匹配单个特征与所有人设特征
  183. Args:
  184. feature_item: 特征信息(包含"特征名称"和"权重")
  185. persona_features: 人设特征列表
  186. category_mapping: 特征分类映射字典
  187. model_name: 使用的模型名称
  188. Returns:
  189. 特征匹配结果
  190. """
  191. feature_name = feature_item.get("特征名称", "")
  192. feature_weight = feature_item.get("权重", 1.0)
  193. match_results = await match_feature_with_persona(
  194. feature_name=feature_name,
  195. persona_features=persona_features,
  196. category_mapping=category_mapping,
  197. model_name=model_name
  198. )
  199. return {
  200. "特征名称": feature_name,
  201. "权重": feature_weight,
  202. "匹配结果": match_results
  203. }
  204. async def process_single_point(
  205. point: Dict,
  206. point_type: str,
  207. persona_features: List[Dict],
  208. category_mapping: Dict = None,
  209. model_name: str = None
  210. ) -> Dict:
  211. """
  212. 处理单个点(灵感点/关键点/目的点)的特征匹配(并发执行)
  213. Args:
  214. point: 点数据(灵感点/关键点/目的点)
  215. point_type: 点类型("灵感点"/"关键点"/"目的点")
  216. persona_features: 人设特征列表
  217. category_mapping: 特征分类映射字典
  218. model_name: 使用的模型名称
  219. Returns:
  220. 包含 how 步骤列表的点数据
  221. """
  222. point_name = point.get("名称", "")
  223. feature_list = point.get("特征列表", [])
  224. # 并发匹配所有特征
  225. tasks = [
  226. match_single_feature(feature_item, persona_features, category_mapping, model_name)
  227. for feature_item in feature_list
  228. ]
  229. feature_match_results = await asyncio.gather(*tasks)
  230. # 构建 how 步骤(根据点类型生成步骤名称)
  231. step_name_mapping = {
  232. "灵感点": "灵感特征分别匹配人设特征",
  233. "关键点": "关键特征分别匹配人设特征",
  234. "目的点": "目的特征分别匹配人设特征"
  235. }
  236. how_step = {
  237. "步骤名称": step_name_mapping.get(point_type, f"{point_type}特征分别匹配人设特征"),
  238. "特征列表": list(feature_match_results)
  239. }
  240. # 返回更新后的点
  241. result = point.copy()
  242. result["how步骤列表"] = [how_step]
  243. return result
  244. async def process_single_task(
  245. task: Dict,
  246. task_index: int,
  247. total_tasks: int,
  248. all_persona_features: List[Dict],
  249. category_mapping: Dict = None,
  250. model_name: str = None
  251. ) -> Dict:
  252. """
  253. 处理单个任务
  254. Args:
  255. task: 任务数据
  256. task_index: 任务索引(从1开始)
  257. total_tasks: 总任务数
  258. all_persona_features: 所有人设特征列表(包含三种层级)
  259. category_mapping: 特征分类映射字典
  260. model_name: 使用的模型名称
  261. Returns:
  262. 包含 how 解构结果的任务
  263. """
  264. post_id = task.get("帖子id", "")
  265. print(f"\n[{task_index}/{total_tasks}] 处理帖子: {post_id}")
  266. # 获取 what 解构结果
  267. what_result = task.get("what解构结果", {})
  268. # 构建 how 解构结果
  269. how_result = {}
  270. # 处理灵感点、关键点和目的点
  271. for point_type in ["灵感点", "关键点", "目的点"]:
  272. point_list_key = f"{point_type}列表"
  273. point_list = what_result.get(point_list_key, [])
  274. if point_list:
  275. # 并发处理所有点
  276. tasks = [
  277. process_single_point(
  278. point=point,
  279. point_type=point_type,
  280. persona_features=all_persona_features,
  281. category_mapping=category_mapping,
  282. model_name=model_name
  283. )
  284. for point in point_list
  285. ]
  286. updated_point_list = await asyncio.gather(*tasks)
  287. # 添加到 how 解构结果
  288. how_result[point_list_key] = list(updated_point_list)
  289. # 更新任务
  290. updated_task = task.copy()
  291. updated_task["how解构结果"] = how_result
  292. return updated_task
  293. async def process_task_list(
  294. task_list: List[Dict],
  295. persona_features_dict: Dict,
  296. category_mapping: Dict = None,
  297. model_name: str = None
  298. ) -> List[Dict]:
  299. """
  300. 处理整个解构任务列表(并发执行)
  301. Args:
  302. task_list: 解构任务列表
  303. persona_features_dict: 人设特征字典(包含灵感点、目的点、关键点)
  304. category_mapping: 特征分类映射字典
  305. model_name: 使用的模型名称
  306. Returns:
  307. 包含 how 解构结果的任务列表
  308. """
  309. global progress_tracker
  310. # 合并三种人设特征(灵感点、关键点、目的点)
  311. all_features = []
  312. for feature_type in ["灵感点", "关键点", "目的点"]:
  313. # 获取该类型的标签特征
  314. type_features = persona_features_dict.get(feature_type, [])
  315. # 为每个特征添加层级信息
  316. for feature in type_features:
  317. feature_with_level = feature.copy()
  318. feature_with_level["人设特征层级"] = feature_type
  319. all_features.append(feature_with_level)
  320. print(f"人设{feature_type}标签特征数量: {len(type_features)}")
  321. # 从分类映射中提取该类型的分类特征
  322. if category_mapping and feature_type in category_mapping:
  323. type_categories = set()
  324. for _, feature_data in category_mapping[feature_type].items():
  325. categories = feature_data.get("所属分类", [])
  326. type_categories.update(categories)
  327. # 转换为特征格式并添加层级信息
  328. for cat in sorted(type_categories):
  329. all_features.append({
  330. "特征名称": cat,
  331. "人设特征层级": feature_type
  332. })
  333. print(f"人设{feature_type}分类特征数量: {len(type_categories)}")
  334. print(f"总特征数量(三种类型的标签+分类): {len(all_features)}")
  335. # 计算总匹配任务数(灵感点、关键点和目的点)
  336. total_match_count = 0
  337. for task in task_list:
  338. what_result = task.get("what解构结果", {})
  339. for point_type in ["灵感点", "关键点", "目的点"]:
  340. point_list = what_result.get(f"{point_type}列表", [])
  341. for point in point_list:
  342. feature_count = len(point.get("特征列表", []))
  343. total_match_count += feature_count * len(all_features)
  344. print(f"处理灵感点、关键点和目的点特征")
  345. print(f"总匹配任务数: {total_match_count:,}")
  346. print()
  347. # 初始化全局进度跟踪器
  348. progress_tracker = ProgressTracker(total_match_count)
  349. # 并发处理所有任务
  350. tasks = [
  351. process_single_task(
  352. task=task,
  353. task_index=i,
  354. total_tasks=len(task_list),
  355. all_persona_features=all_features,
  356. category_mapping=category_mapping,
  357. model_name=model_name
  358. )
  359. for i, task in enumerate(task_list, 1)
  360. ]
  361. updated_task_list = await asyncio.gather(*tasks)
  362. return list(updated_task_list)
  363. async def main():
  364. """主函数"""
  365. # 输入输出路径
  366. script_dir = Path(__file__).parent
  367. project_root = script_dir.parent.parent
  368. data_dir = project_root / "data" / "data_1118"
  369. task_list_file = data_dir / "当前帖子_解构任务列表.json"
  370. persona_features_file = data_dir / "特征名称_帖子来源.json"
  371. category_mapping_file = data_dir / "特征名称_分类映射.json"
  372. output_dir = data_dir / "当前帖子_how解构结果"
  373. # 创建输出目录
  374. output_dir.mkdir(parents=True, exist_ok=True)
  375. print(f"读取解构任务列表: {task_list_file}")
  376. with open(task_list_file, "r", encoding="utf-8") as f:
  377. task_list_data = json.load(f)
  378. print(f"读取人设特征: {persona_features_file}")
  379. with open(persona_features_file, "r", encoding="utf-8") as f:
  380. persona_features_data = json.load(f)
  381. print(f"读取特征分类映射: {category_mapping_file}")
  382. with open(category_mapping_file, "r", encoding="utf-8") as f:
  383. category_mapping = json.load(f)
  384. # 获取任务列表
  385. task_list = task_list_data.get("解构任务列表", [])
  386. print(f"\n总任务数: {len(task_list)}")
  387. # 处理任务列表
  388. updated_task_list = await process_task_list(
  389. task_list=task_list,
  390. persona_features_dict=persona_features_data,
  391. category_mapping=category_mapping,
  392. model_name=None # 使用默认模型
  393. )
  394. # 分文件保存结果
  395. print(f"\n保存结果到: {output_dir}")
  396. for task in updated_task_list:
  397. post_id = task.get("帖子id", "unknown")
  398. output_file = output_dir / f"{post_id}_how.json"
  399. print(f" 保存: {output_file.name}")
  400. with open(output_file, "w", encoding="utf-8") as f:
  401. json.dump(task, f, ensure_ascii=False, indent=4)
  402. print("\n完成!")
  403. # 打印统计信息
  404. total_inspiration_points = 0
  405. total_key_points = 0
  406. total_purpose_points = 0
  407. total_inspiration_features = 0
  408. total_key_features = 0
  409. total_purpose_features = 0
  410. for task in updated_task_list:
  411. how_result = task.get("how解构结果", {})
  412. # 统计灵感点
  413. inspiration_list = how_result.get("灵感点列表", [])
  414. total_inspiration_points += len(inspiration_list)
  415. for point in inspiration_list:
  416. total_inspiration_features += len(point.get("特征列表", []))
  417. # 统计关键点
  418. key_list = how_result.get("关键点列表", [])
  419. total_key_points += len(key_list)
  420. for point in key_list:
  421. total_key_features += len(point.get("特征列表", []))
  422. # 统计目的点
  423. purpose_list = how_result.get("目的点列表", [])
  424. total_purpose_points += len(purpose_list)
  425. for point in purpose_list:
  426. total_purpose_features += len(point.get("特征列表", []))
  427. print(f"\n统计:")
  428. print(f" 处理的帖子数: {len(updated_task_list)}")
  429. print(f" 处理的灵感点数: {total_inspiration_points}")
  430. print(f" 处理的灵感点特征数: {total_inspiration_features}")
  431. print(f" 处理的关键点数: {total_key_points}")
  432. print(f" 处理的关键点特征数: {total_key_features}")
  433. print(f" 处理的目的点数: {total_purpose_points}")
  434. print(f" 处理的目的点特征数: {total_purpose_features}")
  435. if __name__ == "__main__":
  436. asyncio.run(main())