extract_chapter_context.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. extract_chapter_context.py - extract chapter writing context
  5. Features:
  6. - chapter outline snippet
  7. - previous chapter summaries (prefers .webnovel/summaries)
  8. - compact state summary
  9. - ContextManager contract sections (reader_signal / genre_profile / writing_guidance)
  10. """
  11. from __future__ import annotations
  12. import argparse
  13. import json
  14. import re
  15. import sys
  16. from pathlib import Path
  17. from typing import Any, Dict, List
  18. from runtime_compat import enable_windows_utf8_stdio
  19. try:
  20. from chapter_paths import find_chapter_file
  21. except ImportError: # pragma: no cover
  22. from scripts.chapter_paths import find_chapter_file
  23. def _ensure_scripts_path():
  24. scripts_dir = Path(__file__).resolve().parent
  25. if str(scripts_dir) not in sys.path:
  26. sys.path.insert(0, str(scripts_dir))
  27. def find_project_root(start_path: Path | None = None) -> Path:
  28. """Find project root containing `.webnovel` directory."""
  29. if start_path is None:
  30. start_path = Path.cwd()
  31. search_paths = [
  32. start_path,
  33. start_path / "webnovel-project",
  34. start_path.parent,
  35. ]
  36. for path in search_paths:
  37. if (path / ".webnovel").exists():
  38. return path
  39. raise FileNotFoundError("未找到 .webnovel 目录,请确认项目路径")
  40. def extract_chapter_outline(project_root: Path, chapter_num: int) -> str:
  41. """Extract chapter outline segment from volume outline file."""
  42. volume_num = (chapter_num - 1) // 50 + 1
  43. outline_file = project_root / "大纲" / f"第{volume_num}卷 详细大纲.md"
  44. if not outline_file.exists():
  45. return f"⚠️ 大纲文件不存在: {outline_file}"
  46. content = outline_file.read_text(encoding="utf-8")
  47. pattern = rf"###\s*第\s*{chapter_num}\s*章[::]\s*(.+?)(?=###\s*第\s*\d+\s*章|##\s|$)"
  48. match = re.search(pattern, content, re.DOTALL)
  49. if not match:
  50. pattern2 = rf"###\s*第{chapter_num}章[::]\s*(.+?)(?=###\s*第\d+章|##\s|$)"
  51. match = re.search(pattern2, content, re.DOTALL)
  52. if match:
  53. outline = match.group(0).strip()
  54. if len(outline) > 1500:
  55. outline = outline[:1500] + "\n...(已截断)"
  56. return outline
  57. return f"⚠️ 未找到第 {chapter_num} 章的大纲"
  58. def _load_summary_file(project_root: Path, chapter_num: int) -> str:
  59. """Load summary section from `.webnovel/summaries/chNNNN.md`."""
  60. summary_path = project_root / ".webnovel" / "summaries" / f"ch{chapter_num:04d}.md"
  61. if not summary_path.exists():
  62. return ""
  63. text = summary_path.read_text(encoding="utf-8")
  64. summary_match = re.search(r"##\s*剧情摘要\s*\r?\n(.+?)(?=\r?\n##|$)", text, re.DOTALL)
  65. if summary_match:
  66. return summary_match.group(1).strip()
  67. return ""
  68. def extract_chapter_summary(project_root: Path, chapter_num: int) -> str:
  69. """Extract chapter summary, fallback to chapter body head."""
  70. summary = _load_summary_file(project_root, chapter_num)
  71. if summary:
  72. return summary
  73. chapter_file = find_chapter_file(project_root, chapter_num)
  74. if not chapter_file or not chapter_file.exists():
  75. return f"⚠️ 第{chapter_num}章文件不存在"
  76. content = chapter_file.read_text(encoding="utf-8")
  77. summary_match = re.search(r"##\s*本章摘要\s*\r?\n(.+?)(?=\r?\n##|$)", content, re.DOTALL)
  78. if summary_match:
  79. return summary_match.group(1).strip()
  80. stats_match = re.search(r"##\s*本章统计\s*\r?\n(.+?)(?=\r?\n##|$)", content, re.DOTALL)
  81. if stats_match:
  82. return f"[无摘要,仅统计]\n{stats_match.group(1).strip()}"
  83. lines = content.split("\n")
  84. text_lines = [line for line in lines if not line.startswith("#") and line.strip()]
  85. text = "\n".join(text_lines)[:500]
  86. return f"[自动截取前500字]\n{text}..."
  87. def extract_state_summary(project_root: Path) -> str:
  88. """Extract key fields from `.webnovel/state.json`."""
  89. state_file = project_root / ".webnovel" / "state.json"
  90. if not state_file.exists():
  91. return "⚠️ state.json 不存在"
  92. state = json.loads(state_file.read_text(encoding="utf-8"))
  93. summary_parts: List[str] = []
  94. if "progress" in state:
  95. progress = state["progress"]
  96. summary_parts.append(
  97. f"**进度**: 第{progress.get('current_chapter', '?')}章 / {progress.get('total_words', '?')}字"
  98. )
  99. if "protagonist_state" in state:
  100. ps = state["protagonist_state"]
  101. power = ps.get("power", {})
  102. summary_parts.append(f"**主角实力**: {power.get('realm', '?')} {power.get('layer', '?')}层")
  103. summary_parts.append(f"**当前位置**: {ps.get('location', '?')}")
  104. golden_finger = ps.get("golden_finger", {})
  105. summary_parts.append(
  106. f"**金手指**: {golden_finger.get('name', '?')} Lv.{golden_finger.get('level', '?')}"
  107. )
  108. if "strand_tracker" in state:
  109. tracker = state["strand_tracker"]
  110. history = tracker.get("history", [])[-5:]
  111. if history:
  112. items: List[str] = []
  113. for row in history:
  114. if not isinstance(row, dict):
  115. continue
  116. chapter = row.get("chapter", "?")
  117. strand = row.get("strand") or row.get("dominant") or "unknown"
  118. items.append(f"Ch{chapter}:{strand}")
  119. if items:
  120. summary_parts.append(f"**近5章Strand**: {', '.join(items)}")
  121. plot_threads = state.get("plot_threads", {}) if isinstance(state.get("plot_threads"), dict) else {}
  122. foreshadowing = plot_threads.get("foreshadowing", [])
  123. if isinstance(foreshadowing, list) and foreshadowing:
  124. active = [row for row in foreshadowing if row.get("status") in {"active", "未回收"}]
  125. urgent = [row for row in active if row.get("urgency", 0) > 50]
  126. if urgent:
  127. urgent_list = [
  128. f"{row.get('content', '?')[:30]}... (紧急度:{row.get('urgency')})"
  129. for row in urgent[:3]
  130. ]
  131. summary_parts.append(f"**紧急伏笔**: {'; '.join(urgent_list)}")
  132. return "\n".join(summary_parts)
  133. def _load_contract_context(project_root: Path, chapter_num: int) -> Dict[str, Any]:
  134. """Build context via ContextManager and return selected sections."""
  135. _ensure_scripts_path()
  136. from data_modules.config import DataModulesConfig
  137. from data_modules.context_manager import ContextManager
  138. config = DataModulesConfig.from_project_root(project_root)
  139. manager = ContextManager(config)
  140. payload = manager.build_context(
  141. chapter=chapter_num,
  142. template="plot",
  143. use_snapshot=True,
  144. save_snapshot=True,
  145. max_chars=8000,
  146. )
  147. sections = payload.get("sections", {})
  148. return {
  149. "context_contract_version": (payload.get("meta") or {}).get("context_contract_version"),
  150. "context_weight_stage": (payload.get("meta") or {}).get("context_weight_stage"),
  151. "reader_signal": (sections.get("reader_signal") or {}).get("content", {}),
  152. "genre_profile": (sections.get("genre_profile") or {}).get("content", {}),
  153. "writing_guidance": (sections.get("writing_guidance") or {}).get("content", {}),
  154. }
  155. def build_chapter_context_payload(project_root: Path, chapter_num: int) -> Dict[str, Any]:
  156. """Assemble full chapter context payload for text/json output."""
  157. outline = extract_chapter_outline(project_root, chapter_num)
  158. prev_summaries = []
  159. for prev_ch in range(max(1, chapter_num - 2), chapter_num):
  160. summary = extract_chapter_summary(project_root, prev_ch)
  161. prev_summaries.append(f"### 第{prev_ch}章摘要\n{summary}")
  162. state_summary = extract_state_summary(project_root)
  163. contract_context = _load_contract_context(project_root, chapter_num)
  164. return {
  165. "chapter": chapter_num,
  166. "outline": outline,
  167. "previous_summaries": prev_summaries,
  168. "state_summary": state_summary,
  169. "context_contract_version": contract_context.get("context_contract_version"),
  170. "context_weight_stage": contract_context.get("context_weight_stage"),
  171. "reader_signal": contract_context.get("reader_signal", {}),
  172. "genre_profile": contract_context.get("genre_profile", {}),
  173. "writing_guidance": contract_context.get("writing_guidance", {}),
  174. }
  175. def _render_text(payload: Dict[str, Any]) -> str:
  176. chapter_num = payload.get("chapter")
  177. lines: List[str] = []
  178. lines.append(f"# 第 {chapter_num} 章创作上下文")
  179. lines.append("")
  180. lines.append("## 本章大纲")
  181. lines.append("")
  182. lines.append(str(payload.get("outline", "")))
  183. lines.append("")
  184. lines.append("---")
  185. lines.append("")
  186. lines.append("## 前文摘要")
  187. lines.append("")
  188. for item in payload.get("previous_summaries", []):
  189. lines.append(item)
  190. lines.append("")
  191. lines.append("---")
  192. lines.append("")
  193. lines.append("## 当前状态")
  194. lines.append("")
  195. lines.append(str(payload.get("state_summary", "")))
  196. lines.append("")
  197. contract_version = payload.get("context_contract_version")
  198. if contract_version:
  199. lines.append(f"## Contract ({contract_version})")
  200. lines.append("")
  201. stage = payload.get("context_weight_stage")
  202. if stage:
  203. lines.append(f"- 上下文阶段权重: {stage}")
  204. lines.append("")
  205. writing_guidance = payload.get("writing_guidance") or {}
  206. guidance_items = writing_guidance.get("guidance_items") or []
  207. checklist = writing_guidance.get("checklist") or []
  208. checklist_score = writing_guidance.get("checklist_score") or {}
  209. if guidance_items or checklist:
  210. lines.append("## 写作执行建议")
  211. lines.append("")
  212. for idx, item in enumerate(guidance_items, start=1):
  213. lines.append(f"{idx}. {item}")
  214. if checklist:
  215. total_weight = 0.0
  216. required_count = 0
  217. for row in checklist:
  218. if isinstance(row, dict):
  219. try:
  220. total_weight += float(row.get("weight") or 0)
  221. except (TypeError, ValueError):
  222. pass
  223. if row.get("required"):
  224. required_count += 1
  225. lines.append("")
  226. lines.append("### 执行检查清单(可评分)")
  227. lines.append("")
  228. lines.append(f"- 项目数: {len(checklist)}")
  229. lines.append(f"- 总权重: {total_weight:.2f}")
  230. lines.append(f"- 必做项: {required_count}")
  231. lines.append("")
  232. for idx, row in enumerate(checklist, start=1):
  233. if not isinstance(row, dict):
  234. lines.append(f"{idx}. {row}")
  235. continue
  236. label = str(row.get("label") or "").strip() or "未命名项"
  237. weight = row.get("weight")
  238. required_tag = "必做" if row.get("required") else "可选"
  239. verify_hint = str(row.get("verify_hint") or "").strip()
  240. lines.append(f"{idx}. [{required_tag}][w={weight}] {label}")
  241. if verify_hint:
  242. lines.append(f" - 验收: {verify_hint}")
  243. if checklist_score:
  244. lines.append("")
  245. lines.append("### 执行评分")
  246. lines.append("")
  247. lines.append(f"- 评分: {checklist_score.get('score')}")
  248. lines.append(f"- 完成率: {checklist_score.get('completion_rate')}")
  249. lines.append(f"- 必做完成率: {checklist_score.get('required_completion_rate')}")
  250. lines.append("")
  251. reader_signal = payload.get("reader_signal") or {}
  252. review_trend = reader_signal.get("review_trend") or {}
  253. if review_trend:
  254. overall_avg = review_trend.get("overall_avg")
  255. lines.append("## 追读信号")
  256. lines.append("")
  257. lines.append(f"- 最近审查均分: {overall_avg}")
  258. low_ranges = reader_signal.get("low_score_ranges") or []
  259. if low_ranges:
  260. lines.append(f"- 低分区间数: {len(low_ranges)}")
  261. lines.append("")
  262. genre_profile = payload.get("genre_profile") or {}
  263. if genre_profile.get("genre"):
  264. lines.append("## 题材锚定")
  265. lines.append("")
  266. lines.append(f"- 题材: {genre_profile.get('genre')}")
  267. genres = genre_profile.get("genres") or []
  268. if len(genres) > 1:
  269. lines.append(f"- 复合题材: {' + '.join(str(token) for token in genres)}")
  270. composite_hints = genre_profile.get("composite_hints") or []
  271. for row in composite_hints[:2]:
  272. lines.append(f"- {row}")
  273. refs = genre_profile.get("reference_hints") or []
  274. for row in refs[:3]:
  275. lines.append(f"- {row}")
  276. lines.append("")
  277. return "\n".join(lines).rstrip() + "\n"
  278. def main():
  279. parser = argparse.ArgumentParser(description="提取章节创作所需的精简上下文")
  280. parser.add_argument("--chapter", type=int, required=True, help="目标章节号")
  281. parser.add_argument("--project-root", type=str, help="项目根目录")
  282. parser.add_argument("--format", choices=["text", "json"], default="text", help="输出格式")
  283. args = parser.parse_args()
  284. try:
  285. project_root = Path(args.project_root) if args.project_root else find_project_root()
  286. payload = build_chapter_context_payload(project_root, args.chapter)
  287. if args.format == "json":
  288. print(json.dumps(payload, ensure_ascii=False, indent=2))
  289. else:
  290. print(_render_text(payload), end="")
  291. except Exception as exc:
  292. print(f"❌ 错误: {exc}", file=sys.stderr)
  293. sys.exit(1)
  294. if __name__ == "__main__":
  295. if sys.platform == "win32":
  296. enable_windows_utf8_stdio()
  297. main()