match_inspiration_features.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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.hybrid_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. # 使用混合相似度模型(异步调用)
  102. similarity_result = await compare_phrases(
  103. phrase_a=feature_name,
  104. phrase_b=persona_name,
  105. weight_embedding=0.5,
  106. weight_semantic=0.5
  107. )
  108. # 更新进度
  109. if progress_tracker:
  110. progress_tracker.update(1)
  111. # 判断该特征是标签还是分类
  112. feature_type = "分类" # 默认为分类
  113. categories = []
  114. if category_mapping:
  115. # 先在标签特征中查找(灵感点、关键点、目的点)
  116. is_tag_feature = False
  117. for ft in ["灵感点", "关键点", "目的点"]:
  118. if ft in category_mapping:
  119. type_mapping = category_mapping[ft]
  120. if persona_name in type_mapping:
  121. # 找到了,说明是标签特征
  122. feature_type = "标签"
  123. categories = type_mapping[persona_name].get("所属分类", [])
  124. is_tag_feature = True
  125. break
  126. # 如果不是标签特征,检查是否是分类特征
  127. if not is_tag_feature:
  128. # 收集所有分类
  129. all_categories = set()
  130. for ft in ["灵感点", "关键点", "目的点"]:
  131. if ft in category_mapping:
  132. for fname, fdata in category_mapping[ft].items():
  133. cats = fdata.get("所属分类", [])
  134. all_categories.update(cats)
  135. # 如果当前特征名在分类列表中,则是分类特征
  136. if persona_name in all_categories:
  137. feature_type = "分类"
  138. categories = [] # 分类特征本身没有所属分类
  139. # 去重分类
  140. unique_categories = list(dict.fromkeys(categories))
  141. return {
  142. "人设特征名称": persona_name,
  143. "人设特征层级": persona_feature_level,
  144. "特征类型": feature_type,
  145. "特征分类": unique_categories,
  146. "匹配结果": similarity_result
  147. }
  148. async def match_feature_with_persona(
  149. feature_name: str,
  150. persona_features: List[Dict],
  151. category_mapping: Dict = None,
  152. model_name: str = None
  153. ) -> List[Dict]:
  154. """
  155. 将一个特征与人设特征列表进行匹配(并发执行)
  156. Args:
  157. feature_name: 要匹配的特征名称
  158. persona_features: 人设特征列表(包含"特征名称"和"人设特征层级")
  159. category_mapping: 特征分类映射字典
  160. model_name: 使用的模型名称
  161. Returns:
  162. 匹配结果列表
  163. """
  164. # 创建所有匹配任务
  165. tasks = [
  166. match_single_pair(
  167. feature_name,
  168. persona_feature["特征名称"],
  169. persona_feature["人设特征层级"],
  170. category_mapping,
  171. model_name
  172. )
  173. for persona_feature in persona_features
  174. ]
  175. # 并发执行所有匹配
  176. match_results = await asyncio.gather(*tasks)
  177. return list(match_results)
  178. async def match_single_feature(
  179. feature_item: Dict,
  180. persona_features: List[Dict],
  181. category_mapping: Dict = None,
  182. model_name: str = None
  183. ) -> Dict:
  184. """
  185. 匹配单个特征与所有人设特征
  186. Args:
  187. feature_item: 特征信息(包含"特征名称"和"权重")
  188. persona_features: 人设特征列表
  189. category_mapping: 特征分类映射字典
  190. model_name: 使用的模型名称
  191. Returns:
  192. 特征匹配结果
  193. """
  194. feature_name = feature_item.get("特征名称", "")
  195. feature_weight = feature_item.get("权重", 1.0)
  196. match_results = await match_feature_with_persona(
  197. feature_name=feature_name,
  198. persona_features=persona_features,
  199. category_mapping=category_mapping,
  200. model_name=model_name
  201. )
  202. return {
  203. "特征名称": feature_name,
  204. "权重": feature_weight,
  205. "匹配结果": match_results
  206. }
  207. async def process_single_point(
  208. point: Dict,
  209. point_type: str,
  210. persona_features: List[Dict],
  211. category_mapping: Dict = None,
  212. model_name: str = None
  213. ) -> Dict:
  214. """
  215. 处理单个点(灵感点/关键点/目的点)的特征匹配(并发执行)
  216. Args:
  217. point: 点数据(灵感点/关键点/目的点)
  218. point_type: 点类型("灵感点"/"关键点"/"目的点")
  219. persona_features: 人设特征列表
  220. category_mapping: 特征分类映射字典
  221. model_name: 使用的模型名称
  222. Returns:
  223. 包含 how 步骤列表的点数据
  224. """
  225. point_name = point.get("名称", "")
  226. feature_list = point.get("特征列表", [])
  227. # 并发匹配所有特征
  228. tasks = [
  229. match_single_feature(feature_item, persona_features, category_mapping, model_name)
  230. for feature_item in feature_list
  231. ]
  232. feature_match_results = await asyncio.gather(*tasks)
  233. # 构建 how 步骤(根据点类型生成步骤名称)
  234. step_name_mapping = {
  235. "灵感点": "灵感特征分别匹配人设特征",
  236. "关键点": "关键特征分别匹配人设特征",
  237. "目的点": "目的特征分别匹配人设特征"
  238. }
  239. how_step = {
  240. "步骤名称": step_name_mapping.get(point_type, f"{point_type}特征分别匹配人设特征"),
  241. "特征列表": list(feature_match_results)
  242. }
  243. # 返回更新后的点
  244. result = point.copy()
  245. result["how步骤列表"] = [how_step]
  246. return result
  247. async def process_single_task(
  248. task: Dict,
  249. task_index: int,
  250. total_tasks: int,
  251. all_persona_features: List[Dict],
  252. category_mapping: Dict = None,
  253. model_name: str = None
  254. ) -> Dict:
  255. """
  256. 处理单个任务
  257. Args:
  258. task: 任务数据
  259. task_index: 任务索引(从1开始)
  260. total_tasks: 总任务数
  261. all_persona_features: 所有人设特征列表(包含三种层级)
  262. category_mapping: 特征分类映射字典
  263. model_name: 使用的模型名称
  264. Returns:
  265. 包含 how 解构结果的任务
  266. """
  267. post_id = task.get("帖子id", "")
  268. print(f"\n[{task_index}/{total_tasks}] 处理帖子: {post_id}")
  269. # 获取 what 解构结果
  270. what_result = task.get("what解构结果", {})
  271. # 构建 how 解构结果
  272. how_result = {}
  273. # 处理灵感点、关键点和目的点
  274. for point_type in ["灵感点", "关键点", "目的点"]:
  275. point_list_key = f"{point_type}列表"
  276. point_list = what_result.get(point_list_key, [])
  277. if point_list:
  278. # 并发处理所有点
  279. tasks = [
  280. process_single_point(
  281. point=point,
  282. point_type=point_type,
  283. persona_features=all_persona_features,
  284. category_mapping=category_mapping,
  285. model_name=model_name
  286. )
  287. for point in point_list
  288. ]
  289. updated_point_list = await asyncio.gather(*tasks)
  290. # 添加到 how 解构结果
  291. how_result[point_list_key] = list(updated_point_list)
  292. # 更新任务
  293. updated_task = task.copy()
  294. updated_task["how解构结果"] = how_result
  295. return updated_task
  296. async def process_task_list(
  297. task_list: List[Dict],
  298. persona_features_dict: Dict,
  299. category_mapping: Dict = None,
  300. model_name: str = None
  301. ) -> List[Dict]:
  302. """
  303. 处理整个解构任务列表(并发执行)
  304. Args:
  305. task_list: 解构任务列表
  306. persona_features_dict: 人设特征字典(包含灵感点、目的点、关键点)
  307. category_mapping: 特征分类映射字典
  308. model_name: 使用的模型名称
  309. Returns:
  310. 包含 how 解构结果的任务列表
  311. """
  312. global progress_tracker
  313. # 合并三种人设特征(灵感点、关键点、目的点)
  314. all_features = []
  315. for feature_type in ["灵感点", "关键点", "目的点"]:
  316. # 获取该类型的标签特征
  317. type_features = persona_features_dict.get(feature_type, [])
  318. # 为每个特征添加层级信息
  319. for feature in type_features:
  320. feature_with_level = feature.copy()
  321. feature_with_level["人设特征层级"] = feature_type
  322. all_features.append(feature_with_level)
  323. print(f"人设{feature_type}标签特征数量: {len(type_features)}")
  324. # 从分类映射中提取该类型的分类特征
  325. if category_mapping and feature_type in category_mapping:
  326. type_categories = set()
  327. for _, feature_data in category_mapping[feature_type].items():
  328. categories = feature_data.get("所属分类", [])
  329. type_categories.update(categories)
  330. # 转换为特征格式并添加层级信息
  331. for cat in sorted(type_categories):
  332. all_features.append({
  333. "特征名称": cat,
  334. "人设特征层级": feature_type
  335. })
  336. print(f"人设{feature_type}分类特征数量: {len(type_categories)}")
  337. print(f"总特征数量(三种类型的标签+分类): {len(all_features)}")
  338. # 计算总匹配任务数(灵感点、关键点和目的点)
  339. total_match_count = 0
  340. for task in task_list:
  341. what_result = task.get("what解构结果", {})
  342. for point_type in ["灵感点", "关键点", "目的点"]:
  343. point_list = what_result.get(f"{point_type}列表", [])
  344. for point in point_list:
  345. feature_count = len(point.get("特征列表", []))
  346. total_match_count += feature_count * len(all_features)
  347. print(f"处理灵感点、关键点和目的点特征")
  348. print(f"总匹配任务数: {total_match_count:,}")
  349. print()
  350. # 初始化全局进度跟踪器
  351. progress_tracker = ProgressTracker(total_match_count)
  352. # 并发处理所有任务
  353. tasks = [
  354. process_single_task(
  355. task=task,
  356. task_index=i,
  357. total_tasks=len(task_list),
  358. all_persona_features=all_features,
  359. category_mapping=category_mapping,
  360. model_name=model_name
  361. )
  362. for i, task in enumerate(task_list, 1)
  363. ]
  364. updated_task_list = await asyncio.gather(*tasks)
  365. return list(updated_task_list)
  366. async def main():
  367. """主函数"""
  368. # 输入输出路径
  369. script_dir = Path(__file__).parent
  370. project_root = script_dir.parent.parent
  371. data_dir = project_root / "data" / "data_1118"
  372. task_list_file = data_dir / "当前帖子_解构任务列表.json"
  373. persona_features_file = data_dir / "特征名称_帖子来源.json"
  374. category_mapping_file = data_dir / "特征名称_分类映射.json"
  375. output_dir = data_dir / "当前帖子_how解构结果"
  376. # 创建输出目录
  377. output_dir.mkdir(parents=True, exist_ok=True)
  378. print(f"读取解构任务列表: {task_list_file}")
  379. with open(task_list_file, "r", encoding="utf-8") as f:
  380. task_list_data = json.load(f)
  381. print(f"读取人设特征: {persona_features_file}")
  382. with open(persona_features_file, "r", encoding="utf-8") as f:
  383. persona_features_data = json.load(f)
  384. print(f"读取特征分类映射: {category_mapping_file}")
  385. with open(category_mapping_file, "r", encoding="utf-8") as f:
  386. category_mapping = json.load(f)
  387. # 预先加载模型(混合模型会自动处理)
  388. print("\n预加载混合相似度模型...")
  389. await compare_phrases("测试", "测试", weight_embedding=0.5, weight_semantic=0.5)
  390. print("模型预加载完成!\n")
  391. # 获取任务列表
  392. task_list = task_list_data.get("解构任务列表", [])
  393. print(f"总任务数: {len(task_list)}")
  394. # 处理任务列表
  395. updated_task_list = await process_task_list(
  396. task_list=task_list,
  397. persona_features_dict=persona_features_data,
  398. category_mapping=category_mapping,
  399. model_name=None # 使用默认模型
  400. )
  401. # 分文件保存结果
  402. print(f"\n保存结果到: {output_dir}")
  403. for task in updated_task_list:
  404. post_id = task.get("帖子id", "unknown")
  405. output_file = output_dir / f"{post_id}_how.json"
  406. print(f" 保存: {output_file.name}")
  407. with open(output_file, "w", encoding="utf-8") as f:
  408. json.dump(task, f, ensure_ascii=False, indent=4)
  409. print("\n完成!")
  410. # 打印统计信息
  411. total_inspiration_points = 0
  412. total_key_points = 0
  413. total_purpose_points = 0
  414. total_inspiration_features = 0
  415. total_key_features = 0
  416. total_purpose_features = 0
  417. for task in updated_task_list:
  418. how_result = task.get("how解构结果", {})
  419. # 统计灵感点
  420. inspiration_list = how_result.get("灵感点列表", [])
  421. total_inspiration_points += len(inspiration_list)
  422. for point in inspiration_list:
  423. total_inspiration_features += len(point.get("特征列表", []))
  424. # 统计关键点
  425. key_list = how_result.get("关键点列表", [])
  426. total_key_points += len(key_list)
  427. for point in key_list:
  428. total_key_features += len(point.get("特征列表", []))
  429. # 统计目的点
  430. purpose_list = how_result.get("目的点列表", [])
  431. total_purpose_points += len(purpose_list)
  432. for point in purpose_list:
  433. total_purpose_features += len(point.get("特征列表", []))
  434. print(f"\n统计:")
  435. print(f" 处理的帖子数: {len(updated_task_list)}")
  436. print(f" 处理的灵感点数: {total_inspiration_points}")
  437. print(f" 处理的灵感点特征数: {total_inspiration_features}")
  438. print(f" 处理的关键点数: {total_key_points}")
  439. print(f" 处理的关键点特征数: {total_key_features}")
  440. print(f" 处理的目的点数: {total_purpose_points}")
  441. print(f" 处理的目的点特征数: {total_purpose_features}")
  442. if __name__ == "__main__":
  443. asyncio.run(main())