from __future__ import annotations import re from typing import Any def split_markdown_chapters(md: str) -> list[dict[str, Any]]: """按一级标题 # 拆章;无一级标题则整篇一章。""" text = (md or "").replace("\r\n", "\n").replace("\r", "\n").strip() if not text: return [] parts = re.split(r"(?m)^(#{1} .+)$", text) chapters: list[dict[str, Any]] = [] # parts[0] = 前言(无 # 标题时的前缀) preamble = (parts[0] or "").strip() order = 1 if preamble and len(parts) == 1: chapters.append( { "id": "c1", "title": "正文", "order": 1, "content": preamble + "\n", } ) return chapters if preamble: chapters.append( { "id": "c0", "title": "前言", "order": order, "content": preamble + "\n", } ) order += 1 i = 1 while i < len(parts): heading = parts[i].strip() body = parts[i + 1] if i + 1 < len(parts) else "" title = re.sub(r"^#\s+", "", heading).strip() or f"第{order}章" content = f"{heading}\n{body}".strip() + "\n" chapters.append( { "id": f"c{order}", "title": title, "order": order, "content": content, } ) order += 1 i += 2 return chapters def join_markdown_chapters(chapters: list[dict[str, Any]]) -> str: blocks: list[str] = [] for ch in sorted(chapters or [], key=lambda x: x.get("order") or 0): content = (ch.get("content") or "").strip() if content: blocks.append(content) return "\n\n".join(blocks).strip() + ("\n" if blocks else "") def sanitize_local_images(md: str) -> str: """去掉本地绝对路径图片(小程序无法访问),保留 https 图床。""" text = md or "" # markdown images with local paths text = re.sub( r"!\[[^\]]*\]\((?:[A-Za-z]:\\|/)[^)]+\)", "> (本地图片已省略,请改用在线图床链接)", text, ) # html img with local src text = re.sub( r']+src=["\'](?:[A-Za-z]:\\|/)[^"\']+["\'][^>]*>', "> (本地图片已省略,请改用在线图床链接)", text, flags=re.IGNORECASE, ) return text