34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
|
|
"""将 NarrativeAgent / LLM 返回的 JSON 或纯文本规范为 markdown 正文。"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import json
|
|||
|
|
|
|||
|
|
|
|||
|
|
def narrative_to_markdown(narrative: str) -> str:
|
|||
|
|
"""
|
|||
|
|
将 narrative(JSON paragraphs 或纯文本)转为 markdown。
|
|||
|
|
与已删除的 ChapterComposerOrchestrator._to_markdown 行为一致。
|
|||
|
|
"""
|
|||
|
|
if not narrative or not str(narrative).strip():
|
|||
|
|
return ""
|
|||
|
|
stripped = narrative.strip()
|
|||
|
|
if stripped.startswith("{") and "paragraphs" in stripped:
|
|||
|
|
try:
|
|||
|
|
data = json.loads(stripped)
|
|||
|
|
paras = data.get("paragraphs", [])
|
|||
|
|
if isinstance(paras, list):
|
|||
|
|
parts = []
|
|||
|
|
for p in paras:
|
|||
|
|
if isinstance(p, dict):
|
|||
|
|
text = p.get("content", p.get("text", ""))
|
|||
|
|
else:
|
|||
|
|
text = str(p)
|
|||
|
|
if text.strip():
|
|||
|
|
parts.append(text.strip())
|
|||
|
|
return "\n\n".join(parts)
|
|||
|
|
return stripped
|
|||
|
|
except json.JSONDecodeError:
|
|||
|
|
return stripped
|
|||
|
|
return stripped
|