find_pattern.py 20 KB

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