match_inspiration_features.py 17 KB

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