analyze_creation_pattern.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 创作模式分析(完整流程)
  5. 整合三步流程:
  6. 1. 数据准备:根据帖子图谱 + 人设图谱,提取待分析数据
  7. 2. 起点分析:AI分析创意起点
  8. 3. 模式推导:基于共现关系的迭代推导
  9. 输入:帖子图谱 + 人设图谱
  10. 输出:完整的创作模式分析结果
  11. """
  12. import asyncio
  13. import json
  14. from pathlib import Path
  15. from typing import Dict, List, Optional, Set
  16. import sys
  17. # 添加项目根目录到路径
  18. project_root = Path(__file__).parent.parent.parent
  19. sys.path.insert(0, str(project_root))
  20. from lib.llm_cached import analyze, LLMConfig, AnalyzeResult
  21. from lib.my_trace import set_trace_smith as set_trace
  22. from script.data_processing.path_config import PathConfig
  23. # ===== 配置 =====
  24. TASK_NAME = "creation_pattern" # 缓存任务名称
  25. MATCH_SCORE_THRESHOLD = 0.8 # 匹配分数阈值
  26. GLOBAL_RATIO_THRESHOLD = 0.8 # 全局占比阈值
  27. ORIGIN_SCORE_THRESHOLD = 0.8 # 起点分数阈值
  28. # ===== 数据加载 =====
  29. def load_json(file_path: Path) -> Dict:
  30. """加载JSON文件"""
  31. with open(file_path, "r", encoding="utf-8") as f:
  32. return json.load(f)
  33. def get_post_graph_files(config: PathConfig) -> List[Path]:
  34. """获取所有帖子图谱文件"""
  35. post_graph_dir = config.intermediate_dir / "post_graph"
  36. return sorted(post_graph_dir.glob("*_帖子图谱.json"))
  37. # ===== 第一步:数据准备 =====
  38. def extract_post_detail(post_graph: Dict) -> Dict:
  39. """提取帖子详情"""
  40. meta = post_graph.get("meta", {})
  41. post_detail = meta.get("postDetail", {})
  42. return {
  43. "postId": meta.get("postId", ""),
  44. "postTitle": meta.get("postTitle", ""),
  45. "body_text": post_detail.get("body_text", ""),
  46. "images": post_detail.get("images", []),
  47. "video": post_detail.get("video"),
  48. "publish_time": post_detail.get("publish_time", ""),
  49. "like_count": post_detail.get("like_count", 0),
  50. "collect_count": post_detail.get("collect_count", 0),
  51. }
  52. def extract_analysis_nodes(post_graph: Dict, persona_graph: Dict) -> tuple:
  53. """
  54. 提取待分析节点列表
  55. 待分析节点 = 灵感点 + 目的点 + 关键点
  56. """
  57. nodes = post_graph.get("nodes", {})
  58. edges = post_graph.get("edges", {})
  59. persona_nodes = persona_graph.get("nodes", {})
  60. persona_index = persona_graph.get("index", {})
  61. # 1. 收集关键点信息
  62. keypoints = {}
  63. for node_id, node in nodes.items():
  64. if node.get("type") == "标签" and node.get("dimension") == "关键点":
  65. keypoints[node_id] = {
  66. "名称": node.get("name", ""),
  67. "描述": node.get("detail", {}).get("description", ""),
  68. }
  69. # 2. 分析支撑关系
  70. support_map = {}
  71. for edge_id, edge in edges.items():
  72. if edge.get("type") == "支撑":
  73. source_id = edge.get("source", "")
  74. target_id = edge.get("target", "")
  75. if source_id in keypoints:
  76. if target_id not in support_map:
  77. support_map[target_id] = []
  78. support_map[target_id].append(keypoints[source_id])
  79. # 3. 分析关联关系
  80. relation_map = {}
  81. for edge_id, edge in edges.items():
  82. if edge.get("type") == "关联":
  83. source_id = edge.get("source", "")
  84. target_id = edge.get("target", "")
  85. source_name = nodes.get(source_id, {}).get("name", "")
  86. target_name = nodes.get(target_id, {}).get("name", "")
  87. if source_id not in relation_map:
  88. relation_map[source_id] = []
  89. relation_map[source_id].append(target_name)
  90. if target_id not in relation_map:
  91. relation_map[target_id] = []
  92. relation_map[target_id].append(source_name)
  93. # 4. 分析人设匹配
  94. match_map = {}
  95. persona_out_edges = persona_index.get("outEdges", {})
  96. def get_node_info(node_id: str) -> Optional[Dict]:
  97. """获取人设节点的标准信息"""
  98. node = persona_nodes.get(node_id, {})
  99. if not node:
  100. return None
  101. detail = node.get("detail", {})
  102. parent_path = detail.get("parentPath", [])
  103. return {
  104. "节点ID": node_id,
  105. "节点名称": node.get("name", ""),
  106. "节点分类": "/".join(parent_path) if parent_path else "",
  107. "节点维度": node.get("dimension", ""),
  108. "节点类型": node.get("type", ""),
  109. "人设全局占比": detail.get("probGlobal", 0),
  110. "父类下占比": detail.get("probToParent", 0),
  111. }
  112. def get_parent_category_id(node_id: str) -> Optional[str]:
  113. """通过属于边获取父分类节点ID"""
  114. belong_edges = persona_out_edges.get(node_id, {}).get("属于", [])
  115. for edge in belong_edges:
  116. target_id = edge.get("target", "")
  117. target_node = persona_nodes.get(target_id, {})
  118. if target_node.get("type") == "分类":
  119. return target_id
  120. return None
  121. for edge_id, edge in edges.items():
  122. if edge.get("type") == "匹配":
  123. source_id = edge.get("source", "")
  124. target_id = edge.get("target", "")
  125. if source_id.startswith("帖子:") and target_id.startswith("人设:"):
  126. match_score = edge.get("score", 0)
  127. persona_node = persona_nodes.get(target_id, {})
  128. if persona_node:
  129. node_type = persona_node.get("type", "")
  130. match_node_info = get_node_info(target_id)
  131. if not match_node_info:
  132. continue
  133. if node_type == "标签":
  134. category_id = get_parent_category_id(target_id)
  135. else:
  136. category_id = target_id
  137. category_info = None
  138. if category_id:
  139. category_node = persona_nodes.get(category_id, {})
  140. if category_node:
  141. category_detail = category_node.get("detail", {})
  142. category_path = category_detail.get("parentPath", [])
  143. category_info = {
  144. "节点ID": category_id,
  145. "节点名称": category_node.get("name", ""),
  146. "节点分类": "/".join(category_path) if category_path else "",
  147. "节点维度": category_node.get("dimension", ""),
  148. "节点类型": "分类",
  149. "人设全局占比": category_detail.get("probGlobal", 0),
  150. "父类下占比": category_detail.get("probToParent", 0),
  151. "历史共现分类": [],
  152. }
  153. co_occur_edges = persona_out_edges.get(category_id, {}).get("分类共现", [])
  154. co_occur_edges_sorted = sorted(co_occur_edges, key=lambda x: x.get("score", 0), reverse=True)
  155. for co_edge in co_occur_edges_sorted[:5]:
  156. co_target_id = co_edge.get("target", "")
  157. co_score = co_edge.get("score", 0)
  158. co_node = persona_nodes.get(co_target_id, {})
  159. if co_node:
  160. co_detail = co_node.get("detail", {})
  161. co_path = co_detail.get("parentPath", [])
  162. category_info["历史共现分类"].append({
  163. "节点ID": co_target_id,
  164. "节点名称": co_node.get("name", ""),
  165. "节点分类": "/".join(co_path) if co_path else "",
  166. "节点维度": co_node.get("dimension", ""),
  167. "节点类型": "分类",
  168. "人设全局占比": co_detail.get("probGlobal", 0),
  169. "父类下占比": co_detail.get("probToParent", 0),
  170. "共现度": round(co_score, 4),
  171. })
  172. if source_id not in match_map:
  173. match_map[source_id] = []
  174. match_map[source_id].append({
  175. "匹配节点": match_node_info,
  176. "匹配分数": round(match_score, 4),
  177. "所属分类": category_info,
  178. })
  179. # 5. 构建待分析节点列表
  180. analysis_nodes = []
  181. for node_id, node in nodes.items():
  182. if node.get("type") == "标签" and node.get("domain") == "帖子":
  183. dimension = node.get("dimension", "")
  184. if dimension in ["灵感点", "目的点", "关键点"]:
  185. match_info = match_map.get(node_id)
  186. analysis_nodes.append({
  187. "节点ID": node_id,
  188. "节点名称": node.get("name", ""),
  189. "节点分类": node.get("category", ""),
  190. "节点维度": dimension,
  191. "节点类型": node.get("type", ""),
  192. "节点描述": node.get("detail", {}).get("description", ""),
  193. "人设匹配": match_info,
  194. })
  195. # 6. 构建关系列表
  196. relation_list = []
  197. for edge_id, edge in edges.items():
  198. if edge.get("type") == "支撑":
  199. source_id = edge.get("source", "")
  200. target_id = edge.get("target", "")
  201. if source_id in keypoints:
  202. relation_list.append({
  203. "来源节点": source_id,
  204. "目标节点": target_id,
  205. "关系类型": "支撑",
  206. })
  207. seen_relations = set()
  208. for edge_id, edge in edges.items():
  209. if edge.get("type") == "关联":
  210. source_id = edge.get("source", "")
  211. target_id = edge.get("target", "")
  212. key = tuple(sorted([source_id, target_id]))
  213. if key not in seen_relations:
  214. seen_relations.add(key)
  215. relation_list.append({
  216. "来源节点": source_id,
  217. "目标节点": target_id,
  218. "关系类型": "关联",
  219. })
  220. return analysis_nodes, relation_list
  221. def prepare_analysis_data(post_graph: Dict, persona_graph: Dict) -> Dict:
  222. """
  223. 准备完整的分析数据
  224. 输出扁平化的节点列表 + 独立的人设共现关系数据
  225. """
  226. analysis_nodes, relation_list = extract_analysis_nodes(post_graph, persona_graph)
  227. # 扁平化节点,提取人设共现关系数据
  228. flat_nodes = []
  229. persona_co_occur = {} # {分类ID: {名称, 共现分类列表}}
  230. for node in analysis_nodes:
  231. # 基础节点字段
  232. flat_node = {
  233. "节点ID": node["节点ID"],
  234. "节点名称": node["节点名称"],
  235. "节点分类": node.get("节点分类", ""),
  236. "节点维度": node["节点维度"],
  237. "节点描述": node.get("节点描述", ""),
  238. "是否已知": False,
  239. "发现编号": None,
  240. }
  241. # 提取人设匹配信息(list格式,支持多个匹配)
  242. match_list = node.get("人设匹配") or []
  243. if match_list:
  244. flat_node["人设匹配"] = []
  245. for match_info in match_list:
  246. category_info = match_info.get("所属分类")
  247. category_id = category_info.get("节点ID") if category_info else None
  248. # 保留完整的匹配信息,但去掉历史共现分类(拆到外面)
  249. clean_match = {
  250. "匹配节点": match_info.get("匹配节点"),
  251. "匹配分数": match_info.get("匹配分数", 0),
  252. }
  253. if category_info:
  254. # 复制所属分类,但不包含历史共现分类
  255. clean_category = {k: v for k, v in category_info.items() if k != "历史共现分类"}
  256. clean_match["所属分类"] = clean_category
  257. flat_node["人设匹配"].append(clean_match)
  258. # 收集人设共现关系(去重)- 从历史共现分类拆出来
  259. if category_id and category_id not in persona_co_occur:
  260. co_occur_list = category_info.get("历史共现分类", [])
  261. if co_occur_list:
  262. persona_co_occur[category_id] = [
  263. {
  264. "节点ID": c.get("节点ID"),
  265. "节点名称": c.get("节点名称"),
  266. "节点分类": c.get("节点分类", ""),
  267. "节点维度": c.get("节点维度", ""),
  268. "节点类型": c.get("节点类型", ""),
  269. "人设全局占比": c.get("人设全局占比", 0),
  270. "父类下占比": c.get("父类下占比", 0),
  271. "共现度": c.get("共现度", 0),
  272. }
  273. for c in co_occur_list
  274. if c.get("节点ID")
  275. ]
  276. else:
  277. flat_node["人设匹配"] = []
  278. flat_nodes.append(flat_node)
  279. return {
  280. "帖子详情": extract_post_detail(post_graph),
  281. "节点列表": flat_nodes,
  282. "关系列表": relation_list,
  283. "人设共现关系": persona_co_occur,
  284. }
  285. # ===== 第二步:起点分析 =====
  286. def get_best_match(node: Dict) -> Optional[Dict]:
  287. """获取节点的最佳人设匹配(分数最高的)"""
  288. match_list = node.get("人设匹配") or []
  289. if not match_list:
  290. return None
  291. return max(match_list, key=lambda m: m.get("匹配分数", 0))
  292. def get_match_score(node: Dict) -> float:
  293. """获取节点的最高人设匹配分数"""
  294. best_match = get_best_match(node)
  295. if best_match:
  296. return best_match.get("匹配分数", 0)
  297. return 0
  298. def get_category_id(node: Dict) -> Optional[str]:
  299. """获取节点的所属分类ID(最佳匹配的)"""
  300. best_match = get_best_match(node)
  301. if best_match:
  302. category = best_match.get("所属分类")
  303. if category:
  304. return category.get("节点ID")
  305. return None
  306. def get_all_category_ids(node: Dict) -> List[str]:
  307. """获取节点所有匹配的分类ID"""
  308. match_list = node.get("人设匹配") or []
  309. result = []
  310. for m in match_list:
  311. category = m.get("所属分类")
  312. if category and category.get("节点ID"):
  313. result.append(category.get("节点ID"))
  314. return result
  315. def get_category_global_ratio(node: Dict) -> float:
  316. """获取节点所属分类的人设全局占比(最佳匹配的)"""
  317. best_match = get_best_match(node)
  318. if best_match:
  319. category = best_match.get("所属分类")
  320. if category:
  321. return category.get("人设全局占比", 0)
  322. return 0
  323. def is_persona_constant(node: Dict) -> bool:
  324. """判断节点是否为人设常量(匹配分数 >= 0.8 且 分类全局占比 >= 0.8)"""
  325. match_score = get_match_score(node)
  326. global_ratio = get_category_global_ratio(node)
  327. return match_score >= MATCH_SCORE_THRESHOLD and global_ratio >= GLOBAL_RATIO_THRESHOLD
  328. def build_origin_context(nodes: List[Dict]) -> Dict:
  329. """构造AI分析的上下文"""
  330. all_points = []
  331. for node in nodes:
  332. all_points.append({
  333. "名称": node["节点名称"],
  334. "分类": node.get("节点分类", ""),
  335. "维度": node.get("节点维度", ""),
  336. "描述": node.get("节点描述", ""),
  337. "人设匹配度": round(get_match_score(node), 2),
  338. "人设全局占比": round(get_category_global_ratio(node), 2),
  339. })
  340. # 起点候选集(灵感点 + 目的点)
  341. candidates = [
  342. node["节点名称"]
  343. for node in nodes
  344. if node["节点维度"] in ["灵感点", "目的点"]
  345. ]
  346. # 人设常量(匹配分数 >= 0.8 且 分类全局占比 >= 0.8)
  347. constants = [
  348. node["节点名称"]
  349. for node in nodes
  350. if is_persona_constant(node)
  351. ]
  352. return {
  353. "all_points": all_points,
  354. "candidates": candidates,
  355. "constants": constants,
  356. }
  357. def format_origin_prompt(context: Dict) -> str:
  358. """格式化起点分析的prompt"""
  359. all_points = context["all_points"]
  360. candidates = context["candidates"]
  361. constants = context["constants"]
  362. points_text = ""
  363. for p in all_points:
  364. points_text += f"- {p['名称']}\n"
  365. points_text += f" 维度: {p['维度']} | 分类: {p['分类']}\n"
  366. points_text += f" 描述: {p['描述']}\n"
  367. points_text += f" 人设匹配度: {p['人设匹配度']} | 人设全局占比: {p['人设全局占比']}\n"
  368. points_text += "\n"
  369. candidates_text = "、".join(candidates)
  370. constants_text = "、".join(constants) if constants else "无"
  371. prompt = f"""# Role
  372. 你是小红书爆款内容的"逆向工程"专家。你的核心能力是透过内容的表象(视觉/形式),还原创作者最初的脑回路(动机/实质)。
  373. # Task
  374. 我提供一组笔记的【创意标签】和一个【起点候选集】。
  375. 请推理出哪些选项是真正的**创意起点**。
  376. # Input Data
  377. ## 全部创意点
  378. {points_text}
  379. ## 起点候选集
  380. {candidates_text}
  381. ## 来自人设的常量
  382. {constants_text}
  383. # 推理约束
  384. 1. 实质推形式,而不是形式推实质,除非形式是一切创意的起点
  385. 2. 因推果而不是果推因
  386. 3. 无法被其他项或人设推理出的点,即为起点
  387. # Output Format
  388. 请输出一个标准的 JSON 格式。
  389. - Key: 候选集中的词。
  390. - Value: 一个对象,包含:
  391. - `score`: 0.0 到 1.0 的浮点数(代表是起点的可能性)。
  392. - `analysis`: 一句话推理"""
  393. return prompt
  394. async def analyze_origin(nodes: List[Dict], force_llm: bool = False) -> Dict:
  395. """
  396. 执行起点分析
  397. 输入: 节点列表
  398. 输出: 节点列表(加了起点分析、是否已知、发现编号字段)+ 中间结果
  399. """
  400. context = build_origin_context(nodes)
  401. prompt = format_origin_prompt(context)
  402. print(f"\n 起点候选: {len(context['candidates'])} 个")
  403. print(f" 人设常量: {len(context['constants'])} 个")
  404. result = await analyze(
  405. prompt=prompt,
  406. task_name=f"{TASK_NAME}/origin",
  407. force=force_llm,
  408. parse_json=True,
  409. )
  410. # 把分析结果合并到节点
  411. llm_result = result.data or {}
  412. output_nodes = []
  413. current_order = 1 # 已知节点的发现编号计数
  414. for node in nodes:
  415. new_node = dict(node) # 复制原节点
  416. name = node["节点名称"]
  417. if name in llm_result:
  418. score = llm_result[name].get("score", 0)
  419. analysis = llm_result[name].get("analysis", "")
  420. # 加起点分析
  421. new_node["起点分析"] = {
  422. "分数": score,
  423. "说明": analysis,
  424. }
  425. # 高分起点标记为已知
  426. if score >= ORIGIN_SCORE_THRESHOLD:
  427. new_node["是否已知"] = True
  428. new_node["发现编号"] = current_order
  429. current_order += 1
  430. else:
  431. new_node["起点分析"] = None
  432. output_nodes.append(new_node)
  433. return {
  434. "输入上下文": {
  435. "起点候选": context["candidates"],
  436. "人设常量": context["constants"],
  437. },
  438. "中间结果": llm_result,
  439. "输出节点": output_nodes,
  440. "cache_hit": result.cache_hit,
  441. "model": result.model_name,
  442. "log_url": result.log_url,
  443. }
  444. # ===== 第三步:模式推导 =====
  445. def derive_patterns(
  446. nodes: List[Dict],
  447. persona_co_occur: Dict[str, Dict],
  448. ) -> Dict:
  449. """
  450. 基于共现关系的迭代推导
  451. 输入: 带起点分析的节点列表 + 人设共现关系数据
  452. 输出: 节点列表(加了推导轮次、未知原因字段)+ 推导边列表
  453. """
  454. node_by_name: Dict[str, Dict] = {n["节点名称"]: n for n in nodes}
  455. # 构建共现查找表 {节点ID: {共现节点ID: 共现度}}
  456. co_occur_lookup = {}
  457. for cat_id, co_occur_list in persona_co_occur.items():
  458. co_occur_lookup[cat_id] = {
  459. c["节点ID"]: c["共现度"]
  460. for c in co_occur_list
  461. }
  462. # 1. 初始化已知点集合(已经是已知的节点)
  463. known_names: Set[str] = set()
  464. node_round: Dict[str, int] = {} # {节点名称: 加入轮次}
  465. for node in nodes:
  466. if node.get("是否已知"):
  467. known_names.add(node["节点名称"])
  468. node_round[node["节点名称"]] = 0
  469. unknown_names: Set[str] = set(node_by_name.keys()) - known_names
  470. edges: List[Dict] = []
  471. # 2. 迭代推导
  472. round_num = 0
  473. new_known_this_round = known_names.copy()
  474. while new_known_this_round:
  475. round_num += 1
  476. new_known_next_round: Set[str] = set()
  477. for known_name in new_known_this_round:
  478. known_node = node_by_name.get(known_name)
  479. if not known_node:
  480. continue
  481. if get_match_score(known_node) < MATCH_SCORE_THRESHOLD:
  482. continue
  483. # 获取该节点所属分类的共现列表
  484. known_cat_id = get_category_id(known_node)
  485. if not known_cat_id or known_cat_id not in co_occur_lookup:
  486. continue
  487. co_occur_map = co_occur_lookup[known_cat_id]
  488. for unknown_name in list(unknown_names):
  489. unknown_node = node_by_name.get(unknown_name)
  490. if not unknown_node:
  491. continue
  492. if get_match_score(unknown_node) < MATCH_SCORE_THRESHOLD:
  493. continue
  494. # 检查未知节点的分类是否在已知节点的共现列表中
  495. unknown_cat_id = get_category_id(unknown_node)
  496. if unknown_cat_id and unknown_cat_id in co_occur_map:
  497. co_occur_score = co_occur_map[unknown_cat_id]
  498. new_known_next_round.add(unknown_name)
  499. node_round[unknown_name] = round_num
  500. edges.append({
  501. "来源": known_node["节点ID"],
  502. "目标": unknown_node["节点ID"],
  503. "关系类型": "共现推导",
  504. "推导轮次": round_num,
  505. "共现分类ID": unknown_cat_id,
  506. "共现度": co_occur_score,
  507. })
  508. known_names.update(new_known_next_round)
  509. unknown_names -= new_known_next_round
  510. new_known_this_round = new_known_next_round
  511. if not new_known_next_round:
  512. break
  513. # 3. 构建输出节点(只更新是否已知、发现编号)
  514. # 先找出当前最大发现编号
  515. max_order = 0
  516. for node in nodes:
  517. if node.get("发现编号") and node["发现编号"] > max_order:
  518. max_order = node["发现编号"]
  519. # 按推导轮次排序新发现的节点,分配发现编号
  520. new_known_by_round = {}
  521. for name, r in node_round.items():
  522. if r > 0: # 排除起点(轮次0)
  523. if r not in new_known_by_round:
  524. new_known_by_round[r] = []
  525. new_known_by_round[r].append(name)
  526. # 分配发现编号
  527. order_map = {}
  528. current_order = max_order + 1
  529. for r in sorted(new_known_by_round.keys()):
  530. for name in new_known_by_round[r]:
  531. order_map[name] = current_order
  532. current_order += 1
  533. output_nodes = []
  534. for node in nodes:
  535. new_node = dict(node)
  536. name = node["节点名称"]
  537. # 如果是新推导出来的(非起点),更新已知状态和发现编号
  538. if name in node_round and node_round[name] > 0:
  539. new_node["是否已知"] = True
  540. new_node["发现编号"] = order_map.get(name)
  541. output_nodes.append(new_node)
  542. return {
  543. "输出节点": output_nodes,
  544. "推导边列表": edges,
  545. "推导轮次": round_num,
  546. }
  547. # ===== 第四步:下一步分析 =====
  548. def build_next_step_context(known_nodes: List[Dict], unknown_nodes: List[Dict], all_nodes: List[Dict]) -> Dict:
  549. """构造下一步分析的上下文"""
  550. # 已知点信息(按发现顺序排序)
  551. known_sorted = sorted(known_nodes, key=lambda n: n.get("发现编号") or 999)
  552. known_info = []
  553. for n in known_sorted:
  554. info = {
  555. "名称": n["节点名称"],
  556. "维度": n["节点维度"],
  557. "分类": n.get("节点分类", ""),
  558. "描述": n.get("节点描述", ""),
  559. "人设匹配度": round(get_match_score(n), 2),
  560. "人设全局占比": round(get_category_global_ratio(n), 2),
  561. "发现编号": n.get("发现编号"),
  562. }
  563. # 如果有起点分析,加上
  564. if n.get("起点分析"):
  565. info["起点说明"] = n["起点分析"].get("说明", "")
  566. known_info.append(info)
  567. # 未知点信息
  568. unknown_info = []
  569. for n in unknown_nodes:
  570. unknown_info.append({
  571. "名称": n["节点名称"],
  572. "维度": n["节点维度"],
  573. "分类": n.get("节点分类", ""),
  574. "描述": n.get("节点描述", ""),
  575. "人设匹配度": round(get_match_score(n), 2),
  576. "人设全局占比": round(get_category_global_ratio(n), 2),
  577. })
  578. # 人设常量(从全部节点中筛选)
  579. constants = [
  580. n["节点名称"]
  581. for n in all_nodes
  582. if is_persona_constant(n)
  583. ]
  584. return {
  585. "known_nodes": known_info,
  586. "unknown_nodes": unknown_info,
  587. "constants": constants,
  588. }
  589. def format_next_step_prompt(context: Dict) -> str:
  590. """格式化下一步分析的prompt"""
  591. known_text = ""
  592. for i, n in enumerate(context["known_nodes"], 1):
  593. known_text += f"{i}. {n['名称']} ({n['维度']})\n"
  594. known_text += f" 分类: {n['分类']}\n"
  595. known_text += f" 描述: {n['描述']}\n"
  596. known_text += f" 人设匹配度: {n['人设匹配度']} | 人设全局占比: {n['人设全局占比']}\n"
  597. if n.get("起点说明"):
  598. known_text += f" 起点说明: {n['起点说明']}\n"
  599. known_text += "\n"
  600. unknown_text = ""
  601. for n in context["unknown_nodes"]:
  602. unknown_text += f"- {n['名称']} ({n['维度']})\n"
  603. unknown_text += f" 分类: {n['分类']}\n"
  604. unknown_text += f" 描述: {n['描述']}\n"
  605. unknown_text += f" 人设匹配度: {n['人设匹配度']} | 人设全局占比: {n['人设全局占比']}\n\n"
  606. constants = context.get("constants", [])
  607. constants_text = "、".join(constants) if constants else "无"
  608. prompt = f"""# Role
  609. 你是小红书爆款内容的"逆向工程"专家。你的任务是还原创作者的思维路径。
  610. # Task
  611. 基于已知的创意点,推理哪些未知点最可能是创作者**下一步直接想到**的点。
  612. 可以有多个点同时被想到(如果它们在逻辑上是并列的)。
  613. ## 已知点(按发现顺序)
  614. {known_text}
  615. ## 未知点(待推理)
  616. {unknown_text}
  617. ## 人设常量
  618. {constants_text}
  619. # 推理约束
  620. 1. 创作者的思维是有逻辑的:先有动机/目的,再想形式/手法
  621. 2. 关键点通常是为了支撑灵感点或目的点
  622. 3. 人设常量是创作者固有的风格,不需要推理
  623. 4. 只输出"下一步直接能想到"的点,不是所有未知点
  624. # Output Format
  625. 输出 JSON,对每个未知点评分:
  626. - Key: 未知点名称
  627. - Value: 对象,包含:
  628. - `score`: 0.0-1.0(下一步被想到的可能性)
  629. - `from`: 从哪个已知点推导出来(已知点名称)
  630. - `reason`: 如何从该已知点推导出来(一句话)"""
  631. return prompt
  632. async def analyze_next_step(
  633. nodes: List[Dict],
  634. force_llm: bool = False
  635. ) -> Dict:
  636. """
  637. 执行下一步分析
  638. 输入: 节点列表(有已知和未知)
  639. 输出: 最可能的下一步点列表
  640. """
  641. # 分离已知和未知
  642. known_nodes = [n for n in nodes if n.get("是否已知")]
  643. unknown_nodes = [n for n in nodes if not n.get("是否已知")]
  644. if not unknown_nodes:
  645. return {
  646. "输入上下文": {"已知点": [], "未知点": [], "人设常量": []},
  647. "中间结果": [],
  648. "下一步点": [],
  649. }
  650. context = build_next_step_context(known_nodes, unknown_nodes, nodes)
  651. prompt = format_next_step_prompt(context)
  652. print(f"\n 已知点: {len(known_nodes)} 个")
  653. print(f" 未知点: {len(unknown_nodes)} 个")
  654. result = await analyze(
  655. prompt=prompt,
  656. task_name=f"{TASK_NAME}/next_step",
  657. force=force_llm,
  658. parse_json=True,
  659. )
  660. # 解析结果(现在是 {name: {score, from, reason}} 格式)
  661. llm_result = result.data or {}
  662. # 构建候选列表,按分数排序
  663. candidates = []
  664. for name, info in llm_result.items():
  665. candidates.append({
  666. "节点名称": name,
  667. "可能性分数": info.get("score", 0),
  668. "推导来源": info.get("from", ""),
  669. "推理说明": info.get("reason", ""),
  670. })
  671. candidates.sort(key=lambda x: x["可能性分数"], reverse=True)
  672. return {
  673. "输入上下文": {
  674. "已知点": context["known_nodes"],
  675. "未知点": context["unknown_nodes"],
  676. "人设常量": context["constants"],
  677. },
  678. "中间结果": llm_result,
  679. "下一步候选": candidates,
  680. "cache_hit": result.cache_hit,
  681. "model": result.model_name,
  682. "log_url": result.log_url,
  683. }
  684. # ===== 完整流程 =====
  685. def save_result(post_id: str, post_detail: Dict, steps: List, config: PathConfig) -> Path:
  686. """保存结果到文件"""
  687. output_dir = config.intermediate_dir / "creation_pattern"
  688. output_dir.mkdir(parents=True, exist_ok=True)
  689. output_file = output_dir / f"{post_id}_创作模式.json"
  690. result = {
  691. "帖子详情": post_detail,
  692. "步骤列表": steps,
  693. }
  694. with open(output_file, "w", encoding="utf-8") as f:
  695. json.dump(result, f, ensure_ascii=False, indent=2)
  696. print(f" [已保存] {output_file.name}")
  697. return output_file
  698. async def process_single_post(
  699. post_file: Path,
  700. persona_graph: Dict,
  701. config: PathConfig,
  702. force_llm: bool = False,
  703. max_step: int = 3,
  704. ) -> Dict:
  705. """
  706. 处理单个帖子
  707. Args:
  708. force_llm: 强制重新调用LLM(跳过LLM缓存)
  709. max_step: 最多运行到第几步 (1=数据准备, 2=起点分析, 3=模式推导)
  710. """
  711. post_graph = load_json(post_file)
  712. post_id = post_graph.get("meta", {}).get("postId", "unknown")
  713. print(f"\n{'=' * 60}")
  714. print(f"处理帖子: {post_id}")
  715. print("-" * 60)
  716. steps = []
  717. # ===== 步骤1:数据准备 =====
  718. print("\n[步骤1] 数据准备...")
  719. data = prepare_analysis_data(post_graph, persona_graph)
  720. post_detail = data["帖子详情"]
  721. nodes_step1 = data["节点列表"]
  722. relations_step1 = data["关系列表"]
  723. persona_co_occur = data["人设共现关系"]
  724. # 步骤1所有节点都是新的
  725. new_known_step1 = [n["节点名称"] for n in nodes_step1 if n.get("是否已知")]
  726. step1 = {
  727. "步骤": "数据准备",
  728. "输入": {
  729. "帖子图谱": str(post_file.name),
  730. "人设图谱": "人设图谱.json",
  731. },
  732. "输出": {
  733. "新的已知节点": new_known_step1,
  734. "新的边": [],
  735. "节点列表": nodes_step1,
  736. "边列表": relations_step1,
  737. },
  738. "人设共现关系": persona_co_occur,
  739. "摘要": {
  740. "节点数": len(nodes_step1),
  741. "边数": len(relations_step1),
  742. "人设共现数": len(persona_co_occur),
  743. },
  744. }
  745. steps.append(step1)
  746. print(f" 节点数: {len(nodes_step1)}")
  747. print(f" 关系数: {len(relations_step1)}")
  748. print(f" 人设共现数: {len(persona_co_occur)}")
  749. # 步骤1完成,保存
  750. save_result(post_id, post_detail, steps, config)
  751. if max_step == 1:
  752. return {"帖子详情": post_detail, "步骤列表": steps}
  753. # ===== 步骤2:起点分析 =====
  754. print("\n[步骤2] 起点分析...")
  755. origin_result = await analyze_origin(nodes_step1, force_llm=force_llm)
  756. nodes_step2 = origin_result["输出节点"]
  757. # 统计高分起点
  758. def get_origin_score(node):
  759. analysis = node.get("起点分析")
  760. if analysis:
  761. return analysis.get("分数", 0)
  762. return 0
  763. high_score_origins = [
  764. (n["节点名称"], get_origin_score(n))
  765. for n in nodes_step2
  766. if get_origin_score(n) >= 0.7
  767. ]
  768. # 新发现的已知节点(起点)
  769. new_known_nodes = [n["节点名称"] for n in nodes_step2 if n.get("是否已知")]
  770. step2 = {
  771. "步骤": "起点分析",
  772. "输入": {
  773. "节点列表": nodes_step1,
  774. "起点候选": origin_result["输入上下文"]["起点候选"],
  775. "人设常量": origin_result["输入上下文"]["人设常量"],
  776. },
  777. "中间结果": origin_result["中间结果"],
  778. "输出": {
  779. "新的已知节点": new_known_nodes,
  780. "新的边": [],
  781. "节点列表": nodes_step2,
  782. "边列表": relations_step1, # 边没变化
  783. },
  784. "摘要": {
  785. "新已知数": len(new_known_nodes),
  786. "model": origin_result["model"],
  787. "cache_hit": origin_result["cache_hit"],
  788. "log_url": origin_result.get("log_url"),
  789. },
  790. }
  791. steps.append(step2)
  792. print(f" 高分起点 (>=0.7): {len(high_score_origins)} 个")
  793. for name, score in sorted(high_score_origins, key=lambda x: -x[1]):
  794. print(f" ★ {name}: {score:.2f}")
  795. # 步骤2完成,保存
  796. save_result(post_id, post_detail, steps, config)
  797. if max_step == 2:
  798. return {"帖子详情": post_detail, "步骤列表": steps}
  799. # ===== 步骤3:模式推导 =====
  800. print("\n[步骤3] 模式推导...")
  801. derivation_result = derive_patterns(nodes_step2, persona_co_occur)
  802. nodes_step3 = derivation_result["输出节点"]
  803. edges = derivation_result["推导边列表"]
  804. # 统计
  805. known_count = sum(1 for n in nodes_step3 if n.get("是否已知"))
  806. unknown_count = len(nodes_step3) - known_count
  807. # 新发现的已知节点(本步骤推导出来的,不包括之前的起点)
  808. prev_known = {n["节点名称"] for n in nodes_step2 if n.get("是否已知")}
  809. new_known_nodes = [n["节点名称"] for n in nodes_step3 if n.get("是否已知") and n["节点名称"] not in prev_known]
  810. # 合并边列表(原有边 + 推导边)
  811. all_edges = relations_step1 + edges
  812. step3 = {
  813. "步骤": "模式推导",
  814. "输入": {
  815. "节点列表": nodes_step2,
  816. "人设共现关系": persona_co_occur,
  817. },
  818. "输出": {
  819. "新的已知节点": new_known_nodes,
  820. "新的边": edges,
  821. "节点列表": nodes_step3,
  822. "边列表": all_edges,
  823. },
  824. "摘要": {
  825. "已知点数": known_count,
  826. "新已知数": len(new_known_nodes),
  827. "新边数": len(edges),
  828. "未知点数": unknown_count,
  829. },
  830. }
  831. steps.append(step3)
  832. print(f" 已知点: {known_count} 个")
  833. print(f" 推导边: {len(edges)} 条")
  834. print(f" 未知点: {unknown_count} 个")
  835. # 步骤3完成,保存
  836. save_result(post_id, post_detail, steps, config)
  837. if max_step == 3:
  838. return {"帖子详情": post_detail, "步骤列表": steps}
  839. # ===== 步骤4:下一步分析 =====
  840. print("\n[步骤4] 下一步分析...")
  841. next_step_result = await analyze_next_step(nodes_step3, force_llm=force_llm)
  842. # 获取候选列表
  843. candidates = next_step_result["下一步候选"]
  844. # 筛选高分候选 (>= 0.8)
  845. NEXT_STEP_THRESHOLD = 0.8
  846. high_score_candidates = [c for c in candidates if c["可能性分数"] >= NEXT_STEP_THRESHOLD]
  847. # 构建节点名称到节点的映射
  848. node_by_name = {n["节点名称"]: n for n in nodes_step3}
  849. # 找出当前最大发现编号
  850. max_order = max((n.get("发现编号") or 0) for n in nodes_step3)
  851. # 更新节点:把高分候选标记为已知
  852. nodes_step4 = []
  853. new_known_names = []
  854. current_order = max_order + 1
  855. for node in nodes_step3:
  856. new_node = dict(node)
  857. name = node["节点名称"]
  858. # 检查是否在高分候选中
  859. matching = [c for c in high_score_candidates if c["节点名称"] == name]
  860. if matching and not node.get("是否已知"):
  861. new_node["是否已知"] = True
  862. new_node["发现编号"] = current_order
  863. current_order += 1
  864. new_known_names.append(name)
  865. nodes_step4.append(new_node)
  866. # 创建新的边(推导边)
  867. new_edges = []
  868. for c in high_score_candidates:
  869. target_node = node_by_name.get(c["节点名称"])
  870. source_name = c["推导来源"]
  871. source_node = node_by_name.get(source_name)
  872. if target_node and source_node:
  873. new_edges.append({
  874. "来源": source_node["节点ID"],
  875. "目标": target_node["节点ID"],
  876. "关系类型": "AI推导",
  877. "可能性分数": c["可能性分数"],
  878. "推理说明": c["推理说明"],
  879. })
  880. # 合并边列表
  881. all_edges_step4 = all_edges + new_edges
  882. step4 = {
  883. "步骤": "下一步分析",
  884. "输入": {
  885. "已知点": next_step_result["输入上下文"]["已知点"],
  886. "未知点": next_step_result["输入上下文"]["未知点"],
  887. "人设常量": next_step_result["输入上下文"]["人设常量"],
  888. },
  889. "中间结果": next_step_result["中间结果"],
  890. "输出": {
  891. "新的已知节点": new_known_names,
  892. "新的边": new_edges,
  893. "节点列表": nodes_step4,
  894. "边列表": all_edges_step4,
  895. },
  896. "摘要": {
  897. "已知点数": sum(1 for n in nodes_step4 if n.get("是否已知")),
  898. "新已知数": len(new_known_names),
  899. "新边数": len(new_edges),
  900. "未知点数": sum(1 for n in nodes_step4 if not n.get("是否已知")),
  901. "model": next_step_result.get("model"),
  902. "cache_hit": next_step_result.get("cache_hit"),
  903. "log_url": next_step_result.get("log_url"),
  904. },
  905. }
  906. steps.append(step4)
  907. # 打印高分候选
  908. print(f" 候选数: {len(candidates)} 个")
  909. print(f" 高分候选 (>={NEXT_STEP_THRESHOLD}): {len(high_score_candidates)} 个")
  910. for c in high_score_candidates:
  911. print(f" ★ {c['节点名称']} ({c['可能性分数']:.2f}) ← {c['推导来源']}")
  912. print(f" {c['推理说明']}")
  913. # 步骤4完成,保存
  914. save_result(post_id, post_detail, steps, config)
  915. if max_step == 4:
  916. return {"帖子详情": post_detail, "步骤列表": steps}
  917. # ===== 循环:步骤3→步骤4 直到全部已知 =====
  918. iteration = 1
  919. current_nodes = nodes_step4
  920. current_edges = all_edges_step4
  921. MAX_ITERATIONS = 10 # 防止无限循环
  922. while True:
  923. # 检查是否还有未知节点
  924. unknown_count = sum(1 for n in current_nodes if not n.get("是否已知"))
  925. if unknown_count == 0:
  926. print(f"\n[完成] 所有节点已变为已知")
  927. break
  928. if iteration > MAX_ITERATIONS:
  929. print(f"\n[警告] 达到最大迭代次数 {MAX_ITERATIONS},停止循环")
  930. break
  931. # ===== 迭代步骤3:共现推导 =====
  932. print(f"\n[迭代{iteration}-步骤3] 模式推导...")
  933. derivation_result = derive_patterns(current_nodes, persona_co_occur)
  934. nodes_iter3 = derivation_result["输出节点"]
  935. edges_iter3 = derivation_result["推导边列表"]
  936. # 统计新推导的
  937. prev_known_names = {n["节点名称"] for n in current_nodes if n.get("是否已知")}
  938. new_known_step3 = [n["节点名称"] for n in nodes_iter3 if n.get("是否已知") and n["节点名称"] not in prev_known_names]
  939. new_edges_step3 = edges_iter3 # derive_patterns 返回的是本轮新增的边
  940. all_edges_iter3 = current_edges + new_edges_step3
  941. step_iter3 = {
  942. "步骤": f"迭代{iteration}-模式推导",
  943. "输入": {
  944. "节点列表": current_nodes,
  945. "人设共现关系": persona_co_occur,
  946. },
  947. "输出": {
  948. "新的已知节点": new_known_step3,
  949. "新的边": new_edges_step3,
  950. "节点列表": nodes_iter3,
  951. "边列表": all_edges_iter3,
  952. },
  953. "摘要": {
  954. "已知点数": sum(1 for n in nodes_iter3 if n.get("是否已知")),
  955. "新已知数": len(new_known_step3),
  956. "新边数": len(new_edges_step3),
  957. "未知点数": sum(1 for n in nodes_iter3 if not n.get("是否已知")),
  958. },
  959. }
  960. steps.append(step_iter3)
  961. print(f" 新已知: {len(new_known_step3)} 个")
  962. print(f" 新边: {len(new_edges_step3)} 条")
  963. save_result(post_id, post_detail, steps, config)
  964. # 检查是否还有未知
  965. unknown_after_step3 = sum(1 for n in nodes_iter3 if not n.get("是否已知"))
  966. if unknown_after_step3 == 0:
  967. print(f"\n[完成] 所有节点已变为已知")
  968. break
  969. # ===== 迭代步骤4:AI推导 =====
  970. print(f"\n[迭代{iteration}-步骤4] 下一步分析...")
  971. next_step_result = await analyze_next_step(nodes_iter3, force_llm=force_llm)
  972. candidates_iter4 = next_step_result["下一步候选"]
  973. high_score_iter4 = [c for c in candidates_iter4 if c["可能性分数"] >= NEXT_STEP_THRESHOLD]
  974. # 更新节点
  975. node_by_name_iter4 = {n["节点名称"]: n for n in nodes_iter3}
  976. max_order_iter4 = max((n.get("发现编号") or 0) for n in nodes_iter3)
  977. nodes_iter4 = []
  978. new_known_iter4 = []
  979. current_order_iter4 = max_order_iter4 + 1
  980. for node in nodes_iter3:
  981. new_node = dict(node)
  982. name = node["节点名称"]
  983. matching = [c for c in high_score_iter4 if c["节点名称"] == name]
  984. if matching and not node.get("是否已知"):
  985. new_node["是否已知"] = True
  986. new_node["发现编号"] = current_order_iter4
  987. current_order_iter4 += 1
  988. new_known_iter4.append(name)
  989. nodes_iter4.append(new_node)
  990. # 创建新边
  991. new_edges_iter4 = []
  992. for c in high_score_iter4:
  993. target_node = node_by_name_iter4.get(c["节点名称"])
  994. source_node = node_by_name_iter4.get(c["推导来源"])
  995. if target_node and source_node:
  996. new_edges_iter4.append({
  997. "来源": source_node["节点ID"],
  998. "目标": target_node["节点ID"],
  999. "关系类型": "AI推导",
  1000. "可能性分数": c["可能性分数"],
  1001. "推理说明": c["推理说明"],
  1002. })
  1003. all_edges_iter4 = all_edges_iter3 + new_edges_iter4
  1004. step_iter4 = {
  1005. "步骤": f"迭代{iteration}-下一步分析",
  1006. "输入": {
  1007. "已知点": next_step_result["输入上下文"]["已知点"],
  1008. "未知点": next_step_result["输入上下文"]["未知点"],
  1009. "人设常量": next_step_result["输入上下文"]["人设常量"],
  1010. },
  1011. "中间结果": next_step_result["中间结果"],
  1012. "输出": {
  1013. "新的已知节点": new_known_iter4,
  1014. "新的边": new_edges_iter4,
  1015. "节点列表": nodes_iter4,
  1016. "边列表": all_edges_iter4,
  1017. },
  1018. "摘要": {
  1019. "已知点数": sum(1 for n in nodes_iter4 if n.get("是否已知")),
  1020. "新已知数": len(new_known_iter4),
  1021. "新边数": len(new_edges_iter4),
  1022. "未知点数": sum(1 for n in nodes_iter4 if not n.get("是否已知")),
  1023. "model": next_step_result.get("model"),
  1024. "cache_hit": next_step_result.get("cache_hit"),
  1025. },
  1026. }
  1027. steps.append(step_iter4)
  1028. print(f" 新已知: {len(new_known_iter4)} 个")
  1029. print(f" 新边: {len(new_edges_iter4)} 条")
  1030. save_result(post_id, post_detail, steps, config)
  1031. # 如果这轮没有新进展,停止
  1032. if len(new_known_step3) == 0 and len(new_known_iter4) == 0:
  1033. print(f"\n[停止] 本轮无新进展,停止循环")
  1034. break
  1035. # 更新状态,进入下一轮
  1036. current_nodes = nodes_iter4
  1037. current_edges = all_edges_iter4
  1038. iteration += 1
  1039. return {"帖子详情": post_detail, "步骤列表": steps}
  1040. # ===== 主函数 =====
  1041. async def main(
  1042. post_id: str = None,
  1043. all_posts: bool = False,
  1044. force_llm: bool = False,
  1045. max_step: int = 3,
  1046. ):
  1047. """主函数"""
  1048. _, log_url = set_trace()
  1049. config = PathConfig()
  1050. print(f"账号: {config.account_name}")
  1051. print(f"Trace URL: {log_url}")
  1052. # 加载人设图谱
  1053. persona_graph_file = config.intermediate_dir / "人设图谱.json"
  1054. if not persona_graph_file.exists():
  1055. print(f"错误: 人设图谱文件不存在: {persona_graph_file}")
  1056. return
  1057. persona_graph = load_json(persona_graph_file)
  1058. print(f"人设图谱节点数: {len(persona_graph.get('nodes', {}))}")
  1059. # 获取帖子图谱文件
  1060. post_graph_files = get_post_graph_files(config)
  1061. if not post_graph_files:
  1062. print("错误: 没有找到帖子图谱文件")
  1063. return
  1064. # 确定要处理的帖子
  1065. if post_id:
  1066. target_file = next(
  1067. (f for f in post_graph_files if post_id in f.name),
  1068. None
  1069. )
  1070. if not target_file:
  1071. print(f"错误: 未找到帖子 {post_id}")
  1072. return
  1073. files_to_process = [target_file]
  1074. elif all_posts:
  1075. files_to_process = post_graph_files
  1076. else:
  1077. files_to_process = [post_graph_files[0]]
  1078. print(f"待处理帖子数: {len(files_to_process)}")
  1079. # 处理
  1080. results = []
  1081. for i, post_file in enumerate(files_to_process, 1):
  1082. print(f"\n{'#' * 60}")
  1083. print(f"# 处理帖子 {i}/{len(files_to_process)}")
  1084. print(f"{'#' * 60}")
  1085. result = await process_single_post(
  1086. post_file=post_file,
  1087. persona_graph=persona_graph,
  1088. config=config,
  1089. force_llm=force_llm,
  1090. max_step=max_step,
  1091. )
  1092. results.append(result)
  1093. # 汇总
  1094. print(f"\n{'#' * 60}")
  1095. print(f"# 完成! 共处理 {len(results)} 个帖子")
  1096. print(f"{'#' * 60}")
  1097. print(f"Trace: {log_url}")
  1098. print("\n汇总:")
  1099. for result in results:
  1100. post_id = result["帖子详情"]["postId"]
  1101. steps = result.get("步骤列表", [])
  1102. num_steps = len(steps)
  1103. if num_steps == 1:
  1104. step1_summary = steps[0].get("摘要", {})
  1105. print(f" {post_id}: 节点数={step1_summary.get('节点数', 0)} (仅数据准备)")
  1106. elif num_steps == 2:
  1107. step2_summary = steps[1].get("摘要", {})
  1108. print(f" {post_id}: 起点={step2_summary.get('新已知数', 0)} (未推导)")
  1109. elif num_steps == 3:
  1110. step3_summary = steps[2].get("摘要", {})
  1111. print(f" {post_id}: 已知={step3_summary.get('已知点数', 0)}, "
  1112. f"未知={step3_summary.get('未知点数', 0)}")
  1113. elif num_steps >= 4:
  1114. step4_summary = steps[3].get("摘要", {})
  1115. print(f" {post_id}: 已知={step4_summary.get('已知点数', 0)}, "
  1116. f"新已知={step4_summary.get('新已知数', 0)}, "
  1117. f"新边={step4_summary.get('新边数', 0)}, "
  1118. f"未知={step4_summary.get('未知点数', 0)}")
  1119. else:
  1120. print(f" {post_id}: 无步骤数据")
  1121. if __name__ == "__main__":
  1122. import argparse
  1123. parser = argparse.ArgumentParser(description="创作模式分析")
  1124. parser.add_argument("--post-id", type=str, help="帖子ID")
  1125. parser.add_argument("--all-posts", action="store_true", help="处理所有帖子")
  1126. parser.add_argument("--force-llm", action="store_true", help="强制重新调用LLM(跳过LLM缓存)")
  1127. parser.add_argument("--step", type=int, default=5, choices=[1, 2, 3, 4, 5],
  1128. help="运行到第几步 (1=数据准备, 2=起点分析, 3=模式推导, 4=下一步分析, 5=完整循环)")
  1129. args = parser.parse_args()
  1130. asyncio.run(main(
  1131. post_id=args.post_id,
  1132. all_posts=args.all_posts,
  1133. force_llm=args.force_llm,
  1134. max_step=args.step,
  1135. ))