find_pattern.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. """
  2. 查找 Pattern Tool - 从 pattern 库中获取符合条件概率阈值的 pattern
  3. 功能:读取账号的 pattern 库,合并去重后按条件概率筛选,返回 topN 条 pattern(含 pattern 名称、条件概率)。
  4. """
  5. import json
  6. import sys
  7. from pathlib import Path
  8. from typing import Any, Optional
  9. # 保证直接运行或作为包加载时都能解析 utils / tools(IDE 可跳转)
  10. _root = Path(__file__).resolve().parent.parent
  11. if str(_root) not in sys.path:
  12. sys.path.insert(0, str(_root))
  13. from utils.conditional_ratio_calc import calc_pattern_conditional_ratio
  14. from tools.point_match import _load_match_data, match_derivation_to_post_points
  15. from tools.find_tree_node import _load_trees
  16. try:
  17. from agent.tools import tool, ToolResult, ToolContext
  18. except ImportError:
  19. def tool(*args, **kwargs):
  20. return lambda f: f
  21. ToolResult = None # 仅用 main() 测核心逻辑时可无 agent
  22. ToolContext = None
  23. # 与 pattern_data_process 一致的 key 定义
  24. TOP_KEYS = [
  25. "depth_max_with_name",
  26. "depth_mixed",
  27. "depth_max_concrete",
  28. "depth2_medium",
  29. "depth1_abstract",
  30. ]
  31. SUB_KEYS = ["two_x", "one_x", "zero_x"]
  32. _BASE_INPUT = Path(__file__).resolve().parent.parent / "input"
  33. def _build_node_info(account_name: str) -> dict[str, dict]:
  34. """
  35. 构建人设树节点信息映射: node_name -> {
  36. "type": 节点 _type("class" / "ID" 等),
  37. "children": 子节点名称列表(仅分类节点有值),
  38. "siblings": 兄弟节点名称列表(不含自身),
  39. }
  40. """
  41. node_info: dict[str, dict] = {}
  42. def _walk(node_dict: dict):
  43. children_dict = node_dict.get("children") or {}
  44. child_entries = [(n, c) for n, c in children_dict.items() if isinstance(c, dict)]
  45. child_names = [n for n, _ in child_entries]
  46. for name, child in child_entries:
  47. sub_children = child.get("children") or {}
  48. sub_child_names = [n for n, c in sub_children.items() if isinstance(c, dict)]
  49. node_info[name] = {
  50. "type": child.get("_type", ""),
  51. "children": sub_child_names,
  52. "siblings": [n for n in child_names if n != name],
  53. }
  54. _walk(child)
  55. for _dim_name, root in _load_trees(account_name):
  56. _walk(root)
  57. return node_info
  58. def _pattern_file(account_name: str) -> Path:
  59. """pattern 库文件:../input/{account_name}/原始数据/pattern/processed_edge_data.json"""
  60. return _BASE_INPUT / account_name / "原始数据" / "pattern" / "processed_edge_data.json"
  61. def _slim_pattern(p: dict) -> tuple[float, int, list[str], int]:
  62. """提取 name 列表(去重保序)、support、length、post_count。"""
  63. names = [item["name"] for item in (p.get("items") or [])]
  64. seen = set()
  65. unique = []
  66. for n in names:
  67. if n not in seen:
  68. seen.add(n)
  69. unique.append(n)
  70. support = round(float(p.get("support", 0)), 4)
  71. length = int(p.get("length", 0))
  72. post_count = int(p.get("post_count", 0))
  73. return support, length, unique, post_count
  74. def _merge_and_dedupe(patterns: list[dict]) -> list[dict]:
  75. """
  76. 按 items 的 name 集合去重(不区分顺序),留 support 最大;
  77. 输出格式保留 s、l、i(nameA+nameB+nameC)及 post_count,供条件概率计算使用。
  78. """
  79. key_to_best: dict[tuple, tuple[float, int, int]] = {}
  80. for p in patterns:
  81. support, length, unique, post_count = _slim_pattern(p)
  82. if not unique:
  83. continue
  84. key = tuple(sorted(unique))
  85. if key not in key_to_best or support > key_to_best[key][0]:
  86. key_to_best[key] = (support, length, post_count)
  87. out = []
  88. for k, (s, l, post_count) in key_to_best.items():
  89. out.append({
  90. "s": s,
  91. "l": l,
  92. "i": "+".join(k),
  93. "post_count": post_count,
  94. })
  95. out.sort(key=lambda x: x["s"] * x["l"], reverse=True)
  96. return out
  97. def _load_and_merge_patterns(account_name: str) -> list[dict]:
  98. """读取 pattern 库 JSON,按 TOP_KEYS/SUB_KEYS 合并为列表并做合并、去重。"""
  99. path = _pattern_file(account_name)
  100. if not path.is_file():
  101. return []
  102. with open(path, "r", encoding="utf-8") as f:
  103. data = json.load(f)
  104. all_patterns = []
  105. for top in TOP_KEYS:
  106. if top not in data:
  107. continue
  108. block = data[top]
  109. for sub in SUB_KEYS:
  110. all_patterns.extend(block.get(sub) or [])
  111. return _merge_and_dedupe(all_patterns)
  112. def _parse_derived_list(derived_items: list[dict[str, str]]) -> list[tuple[str, str]]:
  113. """将 agent 传入的 [{"topic": "x", "source_node": "y"}, ...] 转为 DerivedItem 列表。"""
  114. out = []
  115. for item in derived_items:
  116. if isinstance(item, dict):
  117. topic = item.get("topic") or item.get("已推导的选题点")
  118. source = item.get("source_node") or item.get("推导来源人设树节点")
  119. if topic is not None and source is not None:
  120. out.append((str(topic).strip(), str(source).strip()))
  121. elif isinstance(item, (list, tuple)) and len(item) >= 2:
  122. out.append((str(item[0]).strip(), str(item[1]).strip()))
  123. return out
  124. def get_patterns_by_conditional_ratio(
  125. account_name: str,
  126. derived_list: list[tuple[str, str]],
  127. conditional_ratio_threshold: float,
  128. top_n: int,
  129. post_id: str = "",
  130. ) -> list[dict[str, Any]]:
  131. """
  132. 从 pattern 库中获取条件概率 >= 阈值的 pattern,按以下优先级排序后返回 top_n 条:
  133. 1. pattern 元素中直接包含已推导选题点(topic)的排最前;
  134. 2. pattern 元素与任意已推导选题点的匹配分 >= 0.8 的次之(从 match_data 文件读取,
  135. key 为 (帖子选题点, 人设树节点),pattern 元素视为人设树节点);
  136. 3. 按条件概率降序;
  137. 4. 按 length 降序。
  138. derived_list 为空时,条件概率使用 pattern 自身的 support(s)。
  139. 返回每项:pattern名称(nameA+nameB+nameC)、条件概率。
  140. """
  141. merged = _load_and_merge_patterns(account_name)
  142. print(f"_load_and_merge_patterns,patterns: {len(merged)}")
  143. if not merged:
  144. return []
  145. base_dir = _BASE_INPUT
  146. scored: list[tuple[dict, float]] = []
  147. if not derived_list:
  148. # derived_items 为空:条件概率取 pattern 本身的 support (s)
  149. for p in merged:
  150. ratio = float(p.get("s", 0))
  151. if ratio >= conditional_ratio_threshold:
  152. scored.append((p, ratio))
  153. else:
  154. for p in merged:
  155. ratio = calc_pattern_conditional_ratio(
  156. account_name, derived_list, p, base_dir=base_dir
  157. )
  158. if ratio >= conditional_ratio_threshold:
  159. scored.append((p, ratio))
  160. derived_topics = {topic for topic, _ in derived_list} if derived_list else set()
  161. # 次优先:从 match_data 文件加载 (帖子选题点, 人设树节点) -> 匹配分,
  162. # 用已推导选题点(topic)作为帖子选题点,pattern 元素作为人设树节点,
  163. # 检查是否存在匹配分 >= 0.8 的组合。
  164. match_lookup: dict[tuple[str, str], float] = {}
  165. if derived_topics and post_id:
  166. match_lookup = _load_match_data(account_name, post_id)
  167. def _sort_key(x: tuple[dict, float]) -> tuple:
  168. p, ratio = x
  169. elements = set(p["i"].split("+"))
  170. has_derived = bool(elements & derived_topics)
  171. has_high_match = False
  172. if not has_derived and match_lookup:
  173. for elem in elements:
  174. for dt in derived_topics:
  175. if match_lookup.get((dt, elem), 0.0) >= 0.8:
  176. has_high_match = True
  177. break
  178. if has_high_match:
  179. break
  180. return (not has_derived, not has_high_match, -ratio, -p["l"])
  181. scored.sort(key=_sort_key)
  182. result = []
  183. for p, ratio in scored[:top_n]:
  184. result.append({
  185. "pattern名称": p["i"],
  186. "条件概率": round(ratio, 6),
  187. })
  188. return result
  189. @tool(
  190. description="按条件概率从 pattern 库中筛选 pattern,优先返回包含已推导选题点的 pattern,并检查每个 pattern 的元素是否与帖子选题点匹配。"
  191. "功能:根据账号与已推导选题点(可选),筛选条件概率不低于阈值的 pattern;当 derived_items 非空时,优先返回 pattern 元素中包含已推导选题点的 pattern;同时对每个 pattern 的所有元素做帖子选题点匹配,匹配结果直接包含在返回数据中。"
  192. "参数:account_name 为账号名;post_id 为帖子ID,用于加载帖子选题点并做匹配判断;derived_items 为已推导选题点列表,每项含 topic(或已推导的选题点)与 source_node(或推导来源人设树节点),可为空,为空时条件概率使用 pattern 自身的 support;conditional_ratio_threshold 为条件概率阈值;top_n 为返回条数上限,默认 100。"
  193. "返回:ToolResult,output 为可读的 pattern 列表文本"
  194. )
  195. async def find_pattern(
  196. account_name: str,
  197. post_id: str,
  198. derived_items: list[dict[str, str]],
  199. conditional_ratio_threshold: float,
  200. top_n: int = 100,
  201. context: Optional[ToolContext] = None,
  202. ) -> ToolResult:
  203. """
  204. 按条件概率阈值从 pattern 库筛选 pattern,返回最多 top_n 条(按条件概率降序)。
  205. 当 derived_items 非空时,优先返回元素中包含已推导选题点的 pattern。
  206. 返回前对每个 pattern 的所有元素做帖子选题点匹配,匹配结果直接包含在返回数据中。
  207. 参数
  208. -------
  209. account_name : 账号名,用于定位该账号的 pattern 库。
  210. post_id : 帖子ID,用于加载帖子选题点并与 pattern 元素做匹配判断。
  211. derived_items : 已推导选题点列表,可为空。非空时每项为字典,需含 topic(或「已推导的选题点」)与 source_node(或「推导来源人设树节点」);为空时各 pattern 的条件概率取其自身 support。
  212. conditional_ratio_threshold : 条件概率阈值,仅返回条件概率 >= 该值的 pattern。
  213. top_n : 返回条数上限,默认 100。
  214. context : 可选,Agent 工具上下文。
  215. 返回
  216. -------
  217. ToolResult:
  218. - title: 结果标题。
  219. - output: 可读的 pattern 列表文本(每行:pattern名称、条件概率、帖子匹配情况)。
  220. "帖子选题点匹配": 无匹配时为 "无",有匹配时为 list[{"pattern元素", "帖子选题点", "匹配分数"}]}。
  221. - 出错时 error 为错误信息。
  222. """
  223. pattern_path = _pattern_file(account_name)
  224. if not pattern_path.is_file():
  225. return ToolResult(
  226. title="Pattern 库不存在",
  227. output=f"pattern 文件不存在: {pattern_path}",
  228. error="Pattern file not found",
  229. )
  230. try:
  231. derived_list = _parse_derived_list(derived_items or [])
  232. items = get_patterns_by_conditional_ratio(
  233. account_name, derived_list, conditional_ratio_threshold, top_n, post_id
  234. )
  235. # 批量收集所有 pattern 元素,统一做一次帖子选题点匹配
  236. if items and post_id:
  237. all_elements: list[str] = []
  238. seen_elements: set[str] = set()
  239. for item in items:
  240. for elem in item["pattern名称"].split("+"):
  241. elem = elem.strip()
  242. if elem and elem not in seen_elements:
  243. all_elements.append(elem)
  244. seen_elements.add(elem)
  245. matched_results = await match_derivation_to_post_points(all_elements, account_name, post_id)
  246. elem_match_map: dict[str, list] = {}
  247. for m in matched_results:
  248. elem_match_map.setdefault(m["推导选题点"], []).append({
  249. "帖子选题点": m["帖子选题点"],
  250. "匹配分数": m["匹配分数"],
  251. })
  252. for item in items:
  253. pattern_matches = []
  254. for elem in item["pattern名称"].split("+"):
  255. elem = elem.strip()
  256. for post_match in elem_match_map.get(elem, []):
  257. pattern_matches.append({
  258. "pattern元素": elem,
  259. "帖子选题点": post_match["帖子选题点"],
  260. "匹配分数": post_match["匹配分数"],
  261. })
  262. # 仅当 pattern 元素匹配到至少 2 个不同帖子选题点时才返回匹配信息,否则为无
  263. distinct_post_points = len({m["帖子选题点"] for m in pattern_matches})
  264. item["帖子选题点匹配"] = (
  265. pattern_matches if distinct_post_points >= 2 else "无"
  266. )
  267. # [临时] 仅保留有帖子选题点匹配的记录(distinct_post_points>=2),方便后续删除
  268. items = [x for x in items if isinstance(x.get("帖子选题点匹配"), list)]
  269. # 对未匹配帖子选题点的 pattern 元素,通过人设树子节点/兄弟节点扩展匹配
  270. if items and post_id:
  271. node_info_map = _build_node_info(account_name)
  272. all_candidates_set: set[str] = set()
  273. item_unmatched_info: list[list[tuple[str, list[str]]]] = []
  274. for item in items:
  275. pattern_matches = item.get("帖子选题点匹配", [])
  276. matched_elems = (
  277. {m["pattern元素"] for m in pattern_matches}
  278. if isinstance(pattern_matches, list) else set()
  279. )
  280. all_elems = [e.strip() for e in item["pattern名称"].split("+")]
  281. unmatched = [e for e in all_elems if e not in matched_elems]
  282. elem_candidates: list[tuple[str, list[str], str]] = []
  283. for elem in unmatched:
  284. info = node_info_map.get(elem)
  285. if not info:
  286. continue
  287. if info["type"] == "class" and info["children"]:
  288. candidates = info["children"]
  289. expand_type = "子节点"
  290. else:
  291. candidates = info["siblings"]
  292. expand_type = "兄弟节点"
  293. if candidates:
  294. elem_candidates.append((elem, candidates, expand_type))
  295. all_candidates_set.update(candidates)
  296. item_unmatched_info.append(elem_candidates)
  297. if all_candidates_set:
  298. candidate_matches = await match_derivation_to_post_points(
  299. list(all_candidates_set), account_name, post_id
  300. )
  301. cand_match_map: dict[str, list[tuple[str, float]]] = {}
  302. for m in candidate_matches:
  303. cand_match_map.setdefault(m["推导选题点"], []).append(
  304. (m["帖子选题点"], m["匹配分数"])
  305. )
  306. for item, elem_cands in zip(items, item_unmatched_info):
  307. for elem, candidates, expand_type in elem_cands:
  308. best_cand, best_pp, best_sc = None, None, -1.0
  309. for cand in candidates:
  310. for pp, sc in cand_match_map.get(cand, []):
  311. if sc > best_sc:
  312. best_cand, best_pp, best_sc = cand, pp, sc
  313. if best_cand is not None:
  314. item["帖子选题点匹配"].append({
  315. "pattern元素": elem,
  316. "帖子选题点": best_pp,
  317. "匹配分数": best_sc,
  318. "扩展节点": best_cand,
  319. "扩展类型": expand_type,
  320. })
  321. # 同一 pattern 内帖子选题点去重:同一帖子选题点出现多次时只保留分数最高的
  322. for item in items:
  323. matches = item.get("帖子选题点匹配")
  324. if not isinstance(matches, list):
  325. continue
  326. best_by_pp: dict[str, dict] = {}
  327. for m in matches:
  328. pp = m["帖子选题点"]
  329. if pp not in best_by_pp or m["匹配分数"] > best_by_pp[pp]["匹配分数"]:
  330. best_by_pp[pp] = m
  331. item["帖子选题点匹配"] = list(best_by_pp.values())
  332. if not items:
  333. output = f"未找到条件概率 >= {conditional_ratio_threshold} 的 pattern"
  334. else:
  335. lines = []
  336. for x in items:
  337. match_info = x.get("帖子选题点匹配", "无")
  338. if isinstance(match_info, list):
  339. match_str = "、".join(
  340. (
  341. f"{m['扩展节点']}({m['pattern元素']}的{m['扩展类型']})→{m['帖子选题点']}({m['匹配分数']})"
  342. if "扩展节点" in m else
  343. f"{m['pattern元素']}→{m['帖子选题点']}({m['匹配分数']})"
  344. )
  345. for m in match_info
  346. )
  347. else:
  348. match_str = str(match_info)
  349. lines.append(f"- {x['pattern名称']}\t条件概率={x['条件概率']}\t帖子选题点匹配={match_str}")
  350. output = "\n".join(lines)
  351. return ToolResult(
  352. title=f"符合条件概率的 Pattern ({account_name}, 阈值={conditional_ratio_threshold})",
  353. output=output,
  354. metadata={
  355. "account_name": account_name,
  356. "conditional_ratio_threshold": conditional_ratio_threshold,
  357. "top_n": top_n,
  358. "count": len(items),
  359. },
  360. )
  361. except Exception as e:
  362. return ToolResult(
  363. title="查找 Pattern 失败",
  364. output=str(e),
  365. error=str(e),
  366. )
  367. def main() -> None:
  368. """本地测试:用家有大志账号、已推导选题点,查询符合条件概率阈值的 pattern(含帖子匹配)。"""
  369. import asyncio
  370. account_name = "家有大志"
  371. post_id = "68fb6a5c000000000302e5de"
  372. # 已推导选题点,每项:已推导的选题点 + 推导来源人设树节点
  373. # derived_items = [
  374. # {"topic": "分享", "source_node": "分享"},
  375. # {"topic": "植入方式", "source_node": "植入方式"},
  376. # {"topic": "叙事结构", "source_node": "叙事结构"},
  377. # ]
  378. derived_items = derived_items = [{"source_node":"分享","topic":"分享"},{"source_node":"叙事结构","topic":"叙事结构"},{"source_node":"图片文字","topic":"图片文字"},{"source_node":"补充说明式","topic":"补充说明式"},{"source_node":"幽默化标题","topic":"幽默化标题"},{"source_node":"标题","topic":"标题"}]
  379. conditional_ratio_threshold = 0.01
  380. top_n = 2000
  381. # 1)直接调用核心函数(不含帖子匹配,仅验证排序逻辑)
  382. # derived_list = _parse_derived_list(derived_items)
  383. # items = get_patterns_by_conditional_ratio(
  384. # account_name, derived_list, conditional_ratio_threshold, top_n, post_id
  385. # )
  386. # print(f"账号: {account_name}, 阈值: {conditional_ratio_threshold}, top_n: {top_n}")
  387. # print(f"共 {len(items)} 条 pattern:\n")
  388. # for x in items:
  389. # print(f" - {x['pattern名称']}\t条件概率={x['条件概率']}")
  390. # 2)有 agent 时通过 tool 接口再跑一遍(含帖子选题点匹配)
  391. if ToolResult is not None:
  392. async def run_tool():
  393. result = await find_pattern(
  394. account_name=account_name,
  395. post_id=post_id,
  396. derived_items=derived_items,
  397. conditional_ratio_threshold=conditional_ratio_threshold,
  398. top_n=top_n,
  399. )
  400. print("\n--- Tool 返回 ---")
  401. print(result.output)
  402. asyncio.run(run_tool())
  403. if __name__ == "__main__":
  404. main()