Files
life-echo/api/app/features/memoir/narrative_to_markdown.py
2026-03-20 15:15:35 +08:00

34 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""将 NarrativeAgent / LLM 返回的 JSON 或纯文本规范为 markdown 正文。"""
from __future__ import annotations
import json
def narrative_to_markdown(narrative: str) -> str:
"""
将 narrativeJSON 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