text_loader.py
1.47 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
from __future__ import annotations
import re
from src.rag.loaders.base import DocumentBlock, register_loader
from src.rag.loaders.common import enrich_blocks
from src.rag.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())