-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive_text_splitter.py
More file actions
202 lines (175 loc) · 8.1 KB
/
recursive_text_splitter.py
File metadata and controls
202 lines (175 loc) · 8.1 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# -*- coding: utf-8 -*-
import re
import uuid
from typing import Callable, List, Optional
import tiktoken
from .base import BaseSplitter
from src.models.document import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from src.utils.config import get_settings
from src.utils.log_manager import get_module_logger
logger = get_module_logger(__name__)
DEFAULT_CHILD_CHUNK_SIZE = 300
DEFAULT_CHILD_CHUNK_OVERLAP = 30
class RecursiveTextSplitter(BaseSplitter):
"""
递归文本分割器。
使用 LangChain 的 RecursiveCharacterTextSplitter。
支持基于字符长度或基于 Token 数量的分割。
"""
def __init__(
self,
mode: str = "token",
encoding_name: str = "cl100k_base",
structure_mode: str = "standard",
parent_chunk_size: Optional[int] = None,
parent_chunk_overlap: Optional[int] = None,
child_chunk_size: Optional[int] = None,
child_chunk_overlap: Optional[int] = None,
):
"""
初始化 RecursiveTextSplitter。
Args:
mode (str): 分割模式,可选 "char" 或 "token"。
encoding_name (str): tiktoken 编码名称。
"""
if structure_mode not in {"standard", "hierarchical"}:
raise ValueError(f"不支持的结构模式: {structure_mode}")
self.mode = mode
self.structure_mode = structure_mode
self.parent_chunk_size = parent_chunk_size
self.parent_chunk_overlap = parent_chunk_overlap
self.child_chunk_size = child_chunk_size
self.child_chunk_overlap = child_chunk_overlap
self.parent_documents: dict[str, dict[str, object]] = {}
self._encoder = tiktoken.get_encoding(encoding_name)
logger.info(
"初始化 RecursiveTextSplitter,模式: %s, 结构模式: %s, 编码: %s",
mode,
structure_mode,
encoding_name,
)
self._init_splitter()
def _get_length_function(self) -> Callable[[str], int]:
"""根据模式返回长度计算函数。"""
if self.mode == "token":
return lambda x: len(self._encoder.encode(x))
return len
def _init_splitter(self):
"""根据当前配置初始化内部分割器。"""
current_settings = get_settings()
self.text_splitter = RecursiveCharacterTextSplitter(
chunk_size=self.parent_chunk_size or current_settings.kb_chunk_size,
chunk_overlap=self.parent_chunk_overlap if self.parent_chunk_overlap is not None else current_settings.kb_chunk_overlap,
separators=current_settings.kb_splitter_separators,
length_function=self._get_length_function(),
is_separator_regex=False
)
logger.info(
"文本分割器已就绪: chunk_size=%s, mode=%s, structure=%s",
self.parent_chunk_size or current_settings.kb_chunk_size,
self.mode,
self.structure_mode,
)
def _build_child_splitter(self) -> RecursiveCharacterTextSplitter:
"""构建子分片器。"""
current_settings = get_settings()
return RecursiveCharacterTextSplitter(
chunk_size=self.child_chunk_size if self.child_chunk_size is not None else current_settings.kb_child_chunk_size,
chunk_overlap=(
self.child_chunk_overlap
if self.child_chunk_overlap is not None
else current_settings.kb_child_chunk_overlap
),
separators=current_settings.kb_splitter_separators,
length_function=self._get_length_function(),
is_separator_regex=False,
)
@staticmethod
def _strip_leading_punctuation(text: str) -> str:
"""去掉分片开头的句号类标点。"""
return re.sub(r"^[\s.。]+", "", text).strip()
def _split_standard_documents(self, documents: List[Document]) -> List[Document]:
"""标准单层分片。"""
all_chunks: List[Document] = []
for doc in documents:
logger.debug(f"正在分割文档: {doc.metadata.get('source', '未知来源')}")
langchain_chunks = self.text_splitter.create_documents([doc.content], metadatas=[doc.metadata])
for i, chunk in enumerate(langchain_chunks):
chunk_content = self._strip_leading_punctuation(chunk.page_content)
if not chunk_content:
continue
chunk_metadata = chunk.metadata.copy()
chunk_id = uuid.uuid4().hex
chunk_metadata["chunk_id"] = chunk_id
chunk_metadata["doc_id"] = chunk_id
chunk_metadata["chunk_index"] = i
chunk_metadata["token_count"] = len(self._encoder.encode(chunk_content))
all_chunks.append(Document(content=chunk_content, metadata=chunk_metadata))
logger.debug(
"文档 '%s' 分割完成,生成 %s 个块。",
doc.metadata.get("source", "未知来源"),
len(langchain_chunks),
)
return all_chunks
def split_hierarchical(self, documents: List[Document]) -> List[Document]:
"""层级分片:先切父块,再切子块。"""
all_chunks: List[Document] = []
child_splitter = self._build_child_splitter()
self.parent_documents = {}
for doc in documents:
logger.debug(f"正在层级分割文档: {doc.metadata.get('source', '未知来源')}")
parent_documents = self.text_splitter.create_documents([doc.content], metadatas=[doc.metadata])
doc_chunk_count = 0
for parent_index, parent_doc in enumerate(parent_documents):
parent_content = self._strip_leading_punctuation(parent_doc.page_content)
if not parent_content:
continue
parent_id = uuid.uuid4().hex
self.parent_documents[parent_id] = {
"content": parent_content,
"metadata": {
**parent_doc.metadata.copy(),
"parent_chunk_index": parent_index,
},
}
child_documents = child_splitter.create_documents([parent_content], metadatas=[parent_doc.metadata])
for child_index, child_doc in enumerate(child_documents):
child_content = self._strip_leading_punctuation(child_doc.page_content)
if not child_content:
continue
child_metadata = child_doc.metadata.copy()
chunk_id = uuid.uuid4().hex
child_metadata["chunk_id"] = chunk_id
child_metadata["doc_id"] = chunk_id
child_metadata["chunk_index"] = child_index
child_metadata["parent_id"] = parent_id
child_metadata["parent_chunk_index"] = parent_index
child_metadata["token_count"] = len(self._encoder.encode(child_content))
all_chunks.append(Document(content=child_content, metadata=child_metadata))
doc_chunk_count += 1
logger.debug(
"文档 '%s' 层级分割完成,生成 %s 个块。",
doc.metadata.get("source", "未知来源"),
doc_chunk_count,
)
return all_chunks
def split(self, documents: List[Document], **kwargs) -> List[Document]:
"""
将文档列表中的文本内容分割成更小的块。
"""
logger.info(f"开始分割 {len(documents)} 个文档。")
# 实时同步最新配置
self._init_splitter()
self.parent_documents = {}
if self.structure_mode == "hierarchical":
all_chunks = self.split_hierarchical(documents)
else:
all_chunks = self._split_standard_documents(documents)
logger.info(
"分割任务完成,总计生成 %s 个文本块 (模式: %s, 结构: %s)。",
len(all_chunks),
self.mode,
self.structure_mode,
)
return all_chunks