markdown.py
2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from __future__ import annotations
import re
from typing import Any
from src.rag.ingestion.loaders.base import DocumentBlock, register_loader
from src.rag.ingestion.loaders.common import enrich_blocks
from src.rag.ingestion.loaders.text import read_text
from src.rag.core.utils import normalize_text
def parse_markdown_text(text: str, inherited: dict[str, Any] | None = None) -> list[DocumentBlock]:
inherited = dict(inherited or {})
if text.startswith("---"):
end = text.find("\n---", 3)
if end != -1:
inherited["frontmatter"] = text[3:end].strip()
text = text[end + 4 :]
blocks: list[DocumentBlock] = []
headings: list[str] = []
buffer: list[str] = []
offset = 0
def flush() -> None:
nonlocal buffer, offset
content = normalize_text("\n".join(buffer))
if content:
block_type = "table" if _looks_like_markdown_table(content) else "paragraph"
blocks.append(
DocumentBlock(
text=content,
block_type=block_type,
title_path=" / ".join(headings),
source_offset=offset,
metadata={
**dict(inherited),
"heading_level": len(headings) if headings else None,
},
)
)
offset += 1
buffer = []
for line in text.splitlines():
match = re.match(r"^(#{1,6})\s+(.+)$", line)
if match:
flush()
level = len(match.group(1))
headings[:] = headings[: level - 1]
headings.append(match.group(2).strip())
else:
buffer.append(line)
flush()
return enrich_blocks(blocks, parse_method="markdown")
def _looks_like_markdown_table(text: str) -> bool:
lines = [line.strip() for line in text.splitlines() if line.strip()]
return len(lines) >= 2 and "|" in lines[0] and re.search(r"\|\s*:?-{3,}:?\s*\|", lines[1])
class MarkdownLoader:
extensions = {".md"}
def load(self, path: str) -> list[DocumentBlock]:
return parse_markdown_text(read_text(path))
register_loader(MarkdownLoader())