decompose.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. """创作知识解构引擎 v2:一帖 → N 颗(how/what/why,含组件颗)→ frameworks.json + payloads.json。
  2. 编排全流程,把 skill 的 phase 文档当 prompt 喂给 LLM(skill 是唯一真源):
  3. ① 读懂:图文帖→extractor 读图;视频帖→video_extract 下载 mp4+原生整段提炼(base64→Gemini)
  4. ② 判颗+类型闸+三lane成形+轻标签:system = phase1-frame.md
  5. ③ 作用域:system = phase2-scope.md → 候选 → scope_link 定位(火山)
  6. ⑤ 组装:代码 → 每颗一个 ingest payload(按类型分拼)
  7. ① 判 is_empty=true(无可提取知识)→ 短路,跳过 ②③⑤。
  8. 数据源:fixture(已有 5 帖)或实时 crawler 取数(新帖)。须在云端跑。用法:PYTHONPATH=. python scripts/decompose.py
  9. """
  10. from __future__ import annotations
  11. import json
  12. import os
  13. from pathlib import Path
  14. from creation_knowledge.config import Settings
  15. from creation_knowledge.integrations import video_extract
  16. from creation_knowledge.integrations.crawler import fetch_post_detail, parse_detail_response
  17. from creation_knowledge.integrations.extractor import GeminiExtractor
  18. from creation_knowledge.integrations.llm import chat_json
  19. from creation_knowledge.prompts import load_prompt
  20. from scripts.scope_link import ScopeLinker
  21. ROOT = Path(__file__).resolve().parent.parent
  22. FIX = ROOT / "tests" / "fixtures"
  23. DATA = ROOT / "data" / "demo"
  24. SKILL = ROOT / "创作知识提取-skill"
  25. PHASE1 = (SKILL / "extraction" / "phase1-frame.md").read_text(encoding="utf-8")
  26. PHASE2 = (SKILL / "extraction" / "phase2-scope.md").read_text(encoding="utf-8")
  27. GATE_ADMIT = load_prompt("gate_admit") # ①.5 创作判定闸:判"是创作"
  28. GATE_REFUTE = load_prompt("gate_refute") # ①.5:挑刺"是制作/越界"
  29. GATE_TIEBREAK = load_prompt("gate_tiebreak") # ①.5:分歧裁决(边界倾向排除)
  30. NORMALIZE = load_prompt("normalize_scope") # ③前:作用域值名词化(③LLM)
  31. GATE_HOW_ADMIT = load_prompt("gate_how_admit") # ②.5 有序性闸:判"真流水线"
  32. GATE_HOW_REFUTE = load_prompt("gate_how_refute") # ②.5:挑"假how(离散构成硬串)"
  33. GATE_HOW_TIEBREAK = load_prompt("gate_how_tiebreak") # ②.5:分歧裁决(边界倾向假how)
  34. # ① 窄表确定性兜底:只放无歧义裸动作动词(绝不放 营造/引导/表达 等名词语素)
  35. _STRIP_VERBS = ("寻找", "定位", "推导", "核验", "提取", "挖掘", "捕捉",
  36. "识别", "梳理", "归纳", "判断", "验证", "确认", "复盘")
  37. _PROTECT = ("营造", "引导", "表达", "塑造", "叙述", "呈现", "刻画",
  38. "升华", "控制", "推进", "转化", "传达") # 名词语素,永不砍
  39. # from: fixture(读 tests/fixtures)/ live(实时 crawler 取数)
  40. SOURCES = [
  41. {"cid": "699308fa0000000016009697", "platform": "xiaohongshu", "from": "fixture"},
  42. {"cid": "698481e1000000000a02a7c1", "platform": "xiaohongshu", "from": "fixture"},
  43. {"cid": "67e2e39b0000000003028ff0", "platform": "xiaohongshu", "from": "fixture"},
  44. {"cid": "680659e8000000001a007a11", "platform": "xiaohongshu", "from": "fixture"},
  45. {"cid": "67e4bdf50000000006028a59", "platform": "xiaohongshu", "from": "fixture"},
  46. {"cid": "7589257893544165455", "platform": "douyin", "from": "live"}, # 抖音视频
  47. {"cid": "6a33655e000000000f0055af", "platform": "xiaohongshu", "from": "live"}, # 无知识
  48. ]
  49. SRC2CN = {"substance": "实质", "form": "形式", "feeling": "感受", "effect": "作用", "intent": "意图"}
  50. TYPE2ATTR = {"how": "how工序", "what": "what构成", "why": "why原理"}
  51. CSTAGE = {"定向", "构思", "结构", "成文", "打磨"} # 创作阶段受控 5 值
  52. REUSE_THRESHOLD = 0.90
  53. # ---------- 取数 ----------
  54. def load_post(src: dict, settings: Settings):
  55. if src["from"] == "fixture":
  56. resp = json.loads((FIX / f"xhs_case_{src['cid']}.json").read_text("utf-8"))
  57. post = parse_detail_response(resp, fallback_content_id=src["cid"])
  58. else:
  59. post = fetch_post_detail(src["cid"], settings=settings)
  60. if not post.url:
  61. post.url = f"https://www.xiaohongshu.com/explore/{src['cid']}"
  62. return post
  63. # ---------- ① 读懂(图文/视频分流) ----------
  64. def _download_images(post) -> list[str]:
  65. """live 图文帖:把 CDN 图下载到本地 /data(避开小红书防盗链),返回本地公开路径;
  66. 单张失败则退回 CDN 直链(至少有 url)。复用 video_extract 的下载器(iOS UA + 平台 Referer)。"""
  67. base = DATA / "xiaohongshu" / post.id
  68. base.mkdir(parents=True, exist_ok=True)
  69. out = []
  70. for n, url in enumerate(post.image_urls, 1):
  71. dst = base / f"image_{n}.webp"
  72. pub = f"/data/demo/xiaohongshu/{post.id}/image_{n}.webp"
  73. try:
  74. if not dst.exists():
  75. dst.write_bytes(video_extract._default_download(url, post.platform))
  76. out.append(pub)
  77. except Exception:
  78. out.append(url)
  79. return out
  80. def read_one(src: dict, post, settings: Settings, extractor: GeminiExtractor):
  81. cid = src["cid"]
  82. if post.video_urls: # 视频帖:下载 mp4 + 原生整段提炼
  83. save = DATA / "douyin" / f"dy_{cid}" / "video.mp4"
  84. pub = f"/data/demo/douyin/dy_{cid}/video.mp4"
  85. ec = video_extract.extract_video(post, settings=settings, save_path=save, public_url=pub)
  86. media = {"type": "video", "video_url": pub, "images": []}
  87. cmap = {c.index: c.content for c in ec.cards}
  88. cards = [{"index": c.index, "content": cmap.get(c.index, ""), "video_url": pub,
  89. "start": c.start, "end": c.end} for c in post.cards] # 段卡:时间戳 + 读到的内容
  90. else: # 图文帖:读图
  91. ec = extractor.extract(post)
  92. if src["from"] == "fixture":
  93. imgs = [f"/data/demo/xiaohongshu/{post.id}/image_{n}.webp" for n in range(1, len(post.image_urls) + 1)]
  94. else:
  95. imgs = _download_images(post) # live 帖:下载 CDN 图到本地 /data,避开防盗链
  96. media = {"type": "image", "video_url": None, "images": imgs}
  97. cmap = {c.index: c.content for c in ec.cards}
  98. cards = [{"index": n, "content": cmap.get(n, ""), "image_url": imgs[n - 1] if n <= len(imgs) else None}
  99. for n in range(1, len(imgs) + 1)] # 每图一张卡:图 url + 读到的内容
  100. parts = [ec.text]
  101. if ec.from_image:
  102. parts.append("【图片要点】\n" + ec.from_image)
  103. parts += [f"【卡片{c.index}】{c.content}" for c in ec.cards if c.content]
  104. return "\n\n".join(p for p in parts if p), bool(ec.is_empty), media, cards
  105. # ---------- ② 判颗+成形+轻标签 ----------
  106. def shape(post, read: str) -> list[dict]:
  107. user = (f"原帖标题:{post.title or '(无)'}\n\n读懂后的完整内容:\n{read}\n\n"
  108. "按上面规则拆颗+判类型+成形+轻标签。作用域字段一律留空 []。"
  109. "只输出 JSON:{\"knowledges\":[ ... 见模板 ... ]}")
  110. return chat_json(PHASE1, user, timeout=120).get("knowledges") or []
  111. # ---------- ①.5 创作判定闸(voting:admit + refute,分歧上 tiebreak;边界倾向排除)----------
  112. def _vote(system: str, read: str, key: str, on_fail: bool) -> bool:
  113. """跑一次判定,取 key 字段为 bool;出错按 on_fail 兜底(避免 API 抖动误杀)。"""
  114. try:
  115. return bool(chat_json(system, read, timeout=90).get(key))
  116. except Exception:
  117. return on_fail
  118. def creation_gate(read: str) -> tuple[bool, str]:
  119. """判这帖是不是【图文/视频内容创作知识】。返回 (in_scope, 说明)。
  120. 甲方案:admit + refute 两票;一致即定;分歧→tiebreak 裁决(边界倾向排除)。
  121. 判定只看 ① 读懂后的内容,不看标题、不数关键词。"""
  122. v_admit = _vote(GATE_ADMIT, read, "in_scope", on_fail=True) # 判"是创作"
  123. v_refute = not _vote(GATE_REFUTE, read, "out_of_scope", on_fail=False) # 挑刺"是制作/越界"→归一成 in_scope
  124. if v_admit == v_refute:
  125. return v_admit, f"admit={v_admit}/refute={v_refute} 一致"
  126. v_tie = _vote(GATE_TIEBREAK, read, "in_scope", on_fail=False) # 分歧裁决,失败也倾向排除
  127. return v_tie, f"admit={v_admit}/refute={v_refute} 分歧→裁决={v_tie}"
  128. # ---------- ②.5 假how根治:有序性审查(层2信号+层3对抗投票)+ 假how重拆为 what/why ----------
  129. def _chain_signals(steps: list[dict]) -> list[str]:
  130. """层2 确定性信号:并列输入(input 不指向前步产出)/ 产出近义。喂给层3当证据。"""
  131. sigs, outs = [], [(s.get("output") or "") for s in steps]
  132. indep = 0
  133. for i, s in enumerate(steps):
  134. if i == 0:
  135. continue
  136. inp = s.get("input") or ""
  137. if not (("←" in inp) or any(o and o[:4] in inp for o in outs[:i])):
  138. indep += 1
  139. if indep >= 2:
  140. sigs.append(f"{indep} 个后步的 input 未指向前步产出(各自起头)")
  141. for i in range(len(outs)):
  142. for j in range(i + 1, len(outs)):
  143. a, b = outs[i], outs[j]
  144. if a and b and (a in b or b in a):
  145. sigs.append(f"步骤{i+1}与{j+1}产出近义({a} / {b})")
  146. break
  147. return sigs
  148. def how_gate(k: dict) -> tuple[bool, str]:
  149. """层3a 有序性闸(对抗投票:admit 判真链 / refute 挑假链 / 分歧裁决,边界倾向假how)。"""
  150. payload = json.dumps({
  151. "purpose": k.get("purpose"),
  152. "steps": [{"input": s.get("input"), "方法": (s.get("directive") or "")[:300], "产出": s.get("output")}
  153. for s in k.get("steps", [])],
  154. "代码信号": _chain_signals(k.get("steps", [])),
  155. }, ensure_ascii=False)
  156. v_admit = _vote(GATE_HOW_ADMIT, payload, "is_real_how", on_fail=True)
  157. v_refute = not _vote(GATE_HOW_REFUTE, payload, "is_fake", on_fail=False) # 不假 → 真
  158. if v_admit == v_refute:
  159. return v_admit, f"admit={v_admit}/refute={v_refute} 一致"
  160. v_tie = _vote(GATE_HOW_TIEBREAK, payload, "is_real_how", on_fail=False)
  161. return v_tie, f"admit={v_admit}/refute={v_refute} 分歧→裁决={v_tie}"
  162. def reshape_nonhow(k: dict) -> list[dict]:
  163. """层3b 假how重拆:只拆成 What/Why 主颗(不要 how/组件)。失败则保留原颗,不丢内容。"""
  164. body = f"目标:{k.get('purpose','')}\n" + "\n".join(
  165. f"- 输入:{s.get('input','')}|方法:{s.get('directive','')}|产出:{s.get('output','')}"
  166. for s in k.get("steps", []))
  167. user = ("【下面这块原被误判为 how 工序,实为「离散构成 / 原理」,请只拆成 What/Why 主颗——"
  168. "每个'是什么/分几类'的构成块拆一颗 What,背后的原理/标准拆一颗 Why;"
  169. "不要 how、不要组件颗,parent 一律 null。作用域字段留空 []。】\n\n"
  170. f"原标题:{k.get('title','')}\n{body}\n\n"
  171. "只输出 JSON:{\"knowledges\":[ ... 仅 what/why,见模板 ... ]}")
  172. try:
  173. out = chat_json(PHASE1, user, timeout=120).get("knowledges") or []
  174. except Exception:
  175. out = []
  176. res = []
  177. for i, nk in enumerate(out, 1):
  178. if nk.get("type") == "how": # 保险:拒绝又冒出来的 how
  179. continue
  180. nk["id"] = f"{k.get('id','k')}r{i}"
  181. nk["role"], nk["parent"] = "主", None
  182. res.append(nk)
  183. return res or [k] # 兜底:没拆出来就保留原颗
  184. def fix_fake_hows(knowledges: list[dict]) -> list[dict]:
  185. """逐颗 how 审查;假how → 重拆为 what/why(替换原颗)。"""
  186. out = []
  187. for k in knowledges:
  188. if k.get("type") == "how" and len(k.get("steps", [])) >= 2:
  189. real, why = how_gate(k)
  190. if not real:
  191. new = reshape_nonhow(k)
  192. print(f" ②.5 假how「{k.get('title')}」({why})→ 重拆 {len(new)} 颗")
  193. out.extend(new)
  194. continue
  195. out.append(k)
  196. return out
  197. # ---------- ③ 作用域候选 + 定位 ----------
  198. def _slim(knowledges: list[dict]) -> list[dict]:
  199. slim = []
  200. for k in knowledges:
  201. e = {"id": k.get("id"), "type": k.get("type"), "title": k.get("title")}
  202. if k.get("type") == "how":
  203. e["steps"] = [{"id": s.get("id"), "input": s.get("input"),
  204. "directive": (s.get("directive") or "")[:500], "output": s.get("output")}
  205. for s in k.get("steps", [])]
  206. else:
  207. e["内容"] = {x: k.get(x) for x in ("界定", "主体", "主张", "支撑") if k.get(x)}
  208. slim.append(e)
  209. return slim
  210. def scope_candidates(knowledges: list[dict]) -> list:
  211. user = ("给下面每颗知识标作用域候选(how 逐步:每个 step 一组;what/why 颗级:整颗一组)。\n"
  212. "只输出 JSON:{\"scopes\":[{\"knowledge_id\":\"k1\",\"step_id\":\"s1\",\"items\":[{\"scope_type\":\"substance\",\"value\":\"…\"}]},"
  213. "{\"knowledge_id\":\"k2\",\"step_id\":null,\"items\":[...]}]}\n\n"
  214. + json.dumps(_slim(knowledges), ensure_ascii=False))
  215. return chat_json(PHASE2, user, timeout=120).get("scopes") or []
  216. def strip_verb_tail(v: str) -> str:
  217. """① 窄表确定性兜底:砍掉值开头/结尾的无歧义裸动词;砍到 <2 字则回退原值。"""
  218. if not v or len(v) < 3:
  219. return v
  220. for verb in _STRIP_VERBS: # 开头裸动词
  221. if v.startswith(verb) and len(v) - len(verb) >= 2:
  222. v = v[len(verb):]
  223. break
  224. for verb in _STRIP_VERBS: # 结尾裸动词(_PROTECT 与之不相交,名词语素天然不在表里)
  225. if v.endswith(verb) and len(v) - len(verb) >= 2:
  226. v = v[:-len(verb)]
  227. break
  228. return v
  229. def nounify_scopes(scopes: list) -> list:
  230. """作用域值名词化(仅 实质/形式/感受/作用):③ 批量 LLM 名词化 → ① 窄表兜底。在定位前做。
  231. 意图豁免:意图值就该是动词(对齐意图树),不名词化、不剥动词。"""
  232. vals = sorted({it["value"] for sc in scopes for it in (sc.get("items") or [])
  233. if it.get("value") and it.get("scope_type") != "intent"})
  234. mp = {}
  235. if vals:
  236. try:
  237. mp = chat_json(NORMALIZE, json.dumps(vals, ensure_ascii=False), timeout=90).get("映射") or {}
  238. except Exception:
  239. mp = {}
  240. for sc in scopes:
  241. for it in sc.get("items") or []:
  242. v = it.get("value")
  243. if not v or it.get("scope_type") == "intent": # 意图原样保留(动词)
  244. continue
  245. it["value"] = strip_verb_tail(mp.get(v) or v) # ③ 映射优先,再 ① 兜底
  246. return scopes
  247. def link_scope(linker: ScopeLinker, scope_type: str, value: str) -> dict:
  248. try:
  249. hits = linker.link(value, source_type=SRC2CN.get(scope_type, scope_type), top_k=3)
  250. except Exception:
  251. hits = []
  252. top = hits[0] if hits else {}
  253. score = float(top.get("score", 0.0))
  254. reuse = score >= REUSE_THRESHOLD and top.get("name")
  255. return {"scope_type": scope_type, "value": top["name"] if reuse else value,
  256. "candidate": value, "link": "复用" if reuse else "新建", "score": round(score, 4),
  257. "top": [{"name": h["name"], "score": h["score"], "path": h.get("path", "")} for h in hits]}
  258. def apply_scopes(knowledges: list[dict], scopes: list, linker: ScopeLinker) -> None:
  259. by_k = {k.get("id"): k for k in knowledges}
  260. for sc in scopes:
  261. k = by_k.get(sc.get("knowledge_id"))
  262. if not k:
  263. continue
  264. linked = [link_scope(linker, it["scope_type"], it["value"])
  265. for it in (sc.get("items") or []) if it.get("scope_type") and it.get("value")]
  266. if k.get("type") == "how" and sc.get("step_id"):
  267. for s in k.get("steps", []):
  268. if s.get("id") == sc["step_id"]:
  269. s["作用域"] = linked
  270. else:
  271. k["作用域"] = (k.get("作用域") or []) + linked
  272. # ---------- ⑤ 组装 ----------
  273. def build_content(k: dict) -> str:
  274. t = k.get("type")
  275. if t == "how":
  276. lines = [f"目标:{k.get('purpose','')}"]
  277. for i, s in enumerate(k.get("steps", []), 1):
  278. lines += [f"步骤{i}",
  279. f" 输入:{s.get('input','')}", f" 方法:{s.get('directive','')}", f" 产出:{s.get('output','')}"]
  280. return "\n".join(lines)
  281. if t == "what":
  282. head = f"界定:{k.get('界定','')}"
  283. if k.get("kind"):
  284. head += f"({k['kind']}型)"
  285. return "\n".join([head] + _sections(k.get("主体")))
  286. return "\n".join([f"主张:{k.get('主张','')}"] + _sections(k.get("支撑")))
  287. def _sections(blocks) -> list[str]:
  288. """把 what.主体 / why.支撑 的自由小节拼成文本行。"""
  289. out = []
  290. for b in blocks or []:
  291. head = b.get("小标题") or ""
  292. form = b.get("形式")
  293. out.append(f"【{head}】" + (f"({form})" if form else ""))
  294. if b.get("内容"):
  295. out.append(f" {b['内容']}")
  296. for it in b.get("条目") or []:
  297. word = it.get("词") or it.get("要素") or ""
  298. cue = it.get("选择线索")
  299. line = f" - {word}:{it.get('说明','')}" if word else f" - {it.get('说明','')}"
  300. if cue:
  301. line += f"(选用:{cue})"
  302. out.append(line)
  303. return out
  304. def build_payload(post, k: dict, how_titles: dict | None = None) -> dict:
  305. how_titles = how_titles or {}
  306. t = k.get("type")
  307. scopes, seen = [], set()
  308. def add(lst):
  309. for sc in lst:
  310. key = (sc["scope_type"], sc["value"])
  311. if key not in seen:
  312. seen.add(key); scopes.append({"scope_type": sc["scope_type"], "value": sc["value"]})
  313. if t == "how":
  314. for s in k.get("steps", []):
  315. add(s.get("作用域", []))
  316. else:
  317. add(k.get("作用域", []))
  318. ext = [{"key": "业务阶段", "type": "str", "value": v} for v in (k.get("业务阶段") or [])]
  319. if t == "how":
  320. cs, cseen = [], set()
  321. for s in k.get("steps", []):
  322. c = s.get("创作阶段")
  323. if c and c not in cseen:
  324. cseen.add(c); cs.append(c)
  325. ext += [{"key": "创作阶段", "type": "str", "value": v} for v in cs]
  326. ext += [{"key": "动作", "type": "str", "value": s["动作"]} for s in k.get("steps", []) if s.get("动作")]
  327. if k.get("role") == "组件" and k.get("parent"):
  328. p = k["parent"]
  329. ext.append({"key": "出自", "type": "str",
  330. "value": f"{how_titles.get(p.get('how_id'), p.get('how_id'))} 第{p.get('step')}步"})
  331. return {"source": {"id": post.id, "source_type": "post", "title": post.title or "",
  332. "author": post.author_name or "", "source_metadata": {"platform": post.platform, "url": post.url}},
  333. "title": k.get("title"), "content": build_content(k),
  334. "dim_creations": ["创作"], "dim_attributes": [TYPE2ATTR.get(t, "how工序")],
  335. "scopes": scopes, "custom_ext": ext}
  336. def main() -> None:
  337. settings = Settings.from_env()
  338. extractor = GeminiExtractor.from_env()
  339. linker = ScopeLinker()
  340. posts_out, payloads = [], []
  341. for src in SOURCES:
  342. cid = src["cid"]
  343. print(f"\n=== {src['platform']} {cid[:10]} ({src['from']}) ===")
  344. try:
  345. post = load_post(src, settings)
  346. read, is_empty, media, cards = read_one(src, post, settings, extractor)
  347. except Exception as exc:
  348. print(f" ✗ 取数/读懂失败:{exc}")
  349. posts_out.append({"post_id": cid, "source_id": cid, "title": f"(取数失败 {cid})",
  350. "platform": src["platform"], "url": "", "media": {"type": "image", "images": []},
  351. "cards": [], "error": str(exc)[:200], "knowledges": []})
  352. continue
  353. meta = {"post_id": cid, "source_id": post.id, "title": post.title or "",
  354. "platform": post.platform, "url": post.url, "media": media, "cards": cards}
  355. if is_empty: # ① 总闸:纯展示/无可提取
  356. print(f" ① 读懂 {len(read)} 字 → ① 判纯展示/无知识,跳过")
  357. posts_out.append({**meta, "no_knowledge": True, "knowledges": []})
  358. continue
  359. in_scope, gate_why = creation_gate(read) # ①.5 创作判定闸(创作 vs 制作 vs 越界)
  360. if not in_scope:
  361. print(f" ① 读懂 {len(read)} 字 → ①.5 闸判【非创作】({gate_why})→ 整帖排除")
  362. posts_out.append({**meta, "no_knowledge": True, "knowledges": []})
  363. continue
  364. print(f" ① 读懂 {len(read)} 字({media['type']})· ①.5 闸:创作({gate_why})")
  365. knowledges = fix_fake_hows(shape(post, read)) # ② 拆颗 → ②.5 假how根治(假how重拆为 what/why)
  366. how_ids = {k.get("id") for k in knowledges if k.get("type") == "how"}
  367. how_titles = {k.get("id"): k.get("title") for k in knowledges if k.get("type") == "how"}
  368. for k in knowledges:
  369. k["业务阶段"] = [b for b in (k.get("业务阶段") or []) if b in ("灵感", "选题", "脚本")] # 守卫:只留合法业务阶段
  370. for s in k.get("steps", []): # 守卫:创作阶段只留合法 5 值,非法(如"定稿/输出")丢弃
  371. if s.get("创作阶段") not in CSTAGE:
  372. s["创作阶段"] = None
  373. if k.get("role") == "组件" and (k.get("parent") or {}).get("how_id") not in how_ids: # 守卫:组件 parent 必指向同帖 how
  374. k["role"] = "主"; k["parent"] = None
  375. print(f" ② {len(knowledges)} 颗:" + ", ".join(f"{k.get('type')}/{k.get('role')}" for k in knowledges))
  376. apply_scopes(knowledges, nounify_scopes(scope_candidates(knowledges)), linker) # ③名词化+①兜底 → 定位
  377. print(" ③⑤ 作用域定位 + 组装")
  378. posts_out.append({**meta, "knowledges": knowledges})
  379. payloads += [build_payload(post, k, how_titles) for k in knowledges]
  380. suffix = os.environ.get("OUT", "") # OUT=_v2 → 写 frameworks_v2.json,不覆盖原版
  381. (ROOT / f"web/frameworks{suffix}.json").write_text(
  382. json.dumps({"count": len(posts_out), "posts": posts_out}, ensure_ascii=False, indent=1), encoding="utf-8")
  383. (ROOT / f"web/payloads{suffix}.json").write_text(
  384. json.dumps(payloads, ensure_ascii=False, indent=2), encoding="utf-8")
  385. print(f"\nwrote {len(posts_out)} posts, {len(payloads)} payloads → web/frameworks{suffix}.json")
  386. if __name__ == "__main__":
  387. main()