markdown.py 2.18 KB
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())