text.py 1.5 KB
from __future__ import annotations

import re

from src.rag.ingestion.loaders.base import DocumentBlock, register_loader
from src.rag.ingestion.loaders.common import enrich_blocks
from src.rag.core.utils import normalize_text


def read_text(path: str) -> str:
    for enc in ["utf-8", "utf-8-sig", "gbk", "latin-1"]:
        try:
            with open(path, "r", encoding=enc) as f:
                return f.read()
        except UnicodeDecodeError:
            continue
    with open(path, "r", encoding="utf-8", errors="replace") as f:
        return f.read()


def split_plain_blocks(text: str, title_path: str = "") -> list[DocumentBlock]:
    text = normalize_text(text)
    parts = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
    blocks: list[DocumentBlock] = []
    cursor = 0
    for idx, part in enumerate(parts):
        start = text.find(part, cursor)
        end = start + len(part) if start >= 0 else None
        cursor = end or cursor
        blocks.append(
            DocumentBlock(
                text=part,
                title_path=title_path,
                source_offset=idx,
                metadata={
                    "char_start": start if start >= 0 else None,
                    "char_end": end,
                },
            )
        )
    return enrich_blocks(blocks, parse_method="plain_text")


class TextLoader:
    extensions = {".txt"}

    def load(self, path: str) -> list[DocumentBlock]:
        return split_plain_blocks(read_text(path))


register_loader(TextLoader())