chunk.py
8.8 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""按 token 分块,保留 Markdown 章节路径。
v1 的两个问题:
1. 按**字符**数切,对中英混排不准,且和模型上下文预算对不上。
2. "标题一变就强制 flush",导致一份 63KB 的需求文档被切成 79 块,其中大量
只有一两行的碎片。碎片块既召回不准,又白白多花一次 LLM 抽取调用。
这里改成:按 token 累积;章节切换时只有在当前块已达 MIN_CHUNK_TOKENS 时才断开,
否则继续并入 —— 短小的子章节会自然地和相邻内容合并。表格与代码块不切断。
"""
from __future__ import annotations
import re
from ..core.llm import count_tokens
_HEADING_RE = re.compile(r"^(#{1,6})\s+(.*)$")
_FENCE_RE = re.compile(r"^\s*(```|~~~)")
_TABLE_ROW_RE = re.compile(r"^\s*\|.*\|\s*$")
# 中文句末标点优先,其次英文
_SENT_SPLIT = re.compile(r"(?<=[。!?;!?;\n])")
def _blocks(text: str) -> list[tuple[str, str, str]]:
"""把文本拆成 (heading_path, kind, block_text)。kind ∈ para|table|code。"""
lines = text.splitlines()
heading_stack: list[str] = []
out: list[tuple[str, str, str]] = []
buf: list[str] = []
kind = "para"
in_code = False
in_table = False
def flush():
nonlocal buf, kind, in_table
if buf:
joined = "\n".join(buf).strip()
if joined:
out.append((" > ".join(h for h in heading_stack if h), kind, joined))
buf = []
kind = "para"
in_table = False
for line in lines:
if _FENCE_RE.match(line):
if in_code:
buf.append(line)
flush()
in_code = False
else:
flush()
in_code = True
kind = "code"
buf.append(line)
continue
if in_code:
buf.append(line)
continue
stripped = line.strip()
m = _HEADING_RE.match(stripped)
if m:
flush()
level = len(m.group(1))
title = m.group(2).strip()
heading_stack = heading_stack[: level - 1]
while len(heading_stack) < level - 1:
heading_stack.append("")
heading_stack.append(title)
continue
is_table_row = bool(_TABLE_ROW_RE.match(line))
if is_table_row and not in_table:
flush()
in_table = True
kind = "table"
elif in_table and not is_table_row:
flush()
if stripped == "":
if not in_table:
flush()
continue
buf.append(line)
if in_code and buf:
flush()
flush()
return out
def _prefix_within(text: str, max_tokens: int) -> int:
"""二分出最长的、token 数不超过 max_tokens 的前缀长度(字符数)。"""
lo, hi = 1, len(text)
while lo < hi:
mid = (lo + hi + 1) // 2
if count_tokens(text[:mid]) <= max_tokens:
lo = mid
else:
hi = mid - 1
return lo
def _hard_split(text: str, max_tokens: int) -> list[str]:
"""无标点可切时按 token 预算硬切。必须按预算切,不能简单对半分 ——
对半分只保证最后一片达标,前面几片仍然可能是预算的好几倍。"""
out: list[str] = []
rest = text
while count_tokens(rest) > max_tokens:
cut = _prefix_within(rest, max_tokens)
out.append(rest[:cut])
rest = rest[cut:]
if rest:
out.append(rest)
return out
def _split_oversize(text: str, max_tokens: int) -> list[str]:
"""超长单块按句子边界切;切不动(无标点长串、一整张巨表)就按预算硬切。"""
if count_tokens(text) <= max_tokens:
return [text]
units = [u for u in _SENT_SPLIT.split(text) if u]
if len(units) <= 1:
units = text.splitlines(keepends=True) or [text]
pieces: list[str] = []
cur = ""
for u in units:
# 单个 unit 自身就超限,先把它拆开再参与累积
for part in (_hard_split(u, max_tokens) if count_tokens(u) > max_tokens else [u]):
if cur and count_tokens(cur + part) > max_tokens:
pieces.append(cur)
cur = part
else:
cur += part
if cur.strip():
pieces.append(cur)
return pieces
def _tail(text: str, overlap_tokens: int) -> str:
"""取末尾约 overlap_tokens 个 token 作为下一块的前文。"""
if overlap_tokens <= 0 or not text:
return ""
lo, hi = 0, len(text)
while lo < hi:
mid = (lo + hi + 1) // 2
if count_tokens(text[-mid:]) <= overlap_tokens:
lo = mid
else:
hi = mid - 1
return text[-lo:] if lo else ""
def _path(heading: str) -> list[str]:
return [p for p in (heading or "").split(" > ") if p]
def _common_prefix(a: list[str], b: list[str]) -> list[str]:
out = []
for x, y in zip(a, b):
if x != y:
break
out.append(x)
return out
def _same_branch(a: str, b: str) -> bool:
"""两个章节是否同属一棵子树(至少共享顶层父节点)。
只允许在同一分支内合并小节,跨大章节绝不合并 —— 否则 chunk 的 heading
会退化成没有意义的根标题,引用溯源就失真了。
"""
pa, pb = _path(a), _path(b)
if not pa or not pb:
return True
return _common_prefix(pa, pb) == pa[:len(_common_prefix(pa, pb))] and bool(_common_prefix(pa, pb))
def chunk_text(text: str, doc_id: int, chunk_tokens: int = 600,
overlap_tokens: int = 80, min_tokens: int = 120) -> list[dict]:
"""返回 [{"id","order","heading","text","tokens","doc_id","headings"}]。
id 形如 `d3:c0` —— 带 doc_id 前缀。v1 用全局 `c0/c1`,多文档必然冲突。
累积策略:贪心填到 chunk_tokens。章节切换时,只要**同属一棵子树**且预算还够
就继续合并;chunk 的 heading 取其中所有小节的最长公共前缀。
这样一份有 78 个小节、每节中位数才 167 token 的需求文档,不会像 v1 那样
被切成 79 个碎片块(碎片既召回不准,又白白多花一次 LLM 抽取调用)。
"""
blocks = _blocks(text)
chunks: list[dict] = []
order = 0
cur_text = ""
cur_headings: list[str] = []
def chunk_heading() -> str:
if not cur_headings:
return ""
if len(cur_headings) == 1:
return cur_headings[0]
prefix = _path(cur_headings[0])
for h in cur_headings[1:]:
prefix = _common_prefix(prefix, _path(h))
if not prefix:
break
return " > ".join(prefix) if prefix else cur_headings[0]
def emit():
nonlocal order, cur_text, cur_headings
t = cur_text.strip()
if t:
chunks.append({"id": f"d{doc_id}:c{order}", "order": order, "doc_id": doc_id,
"heading": chunk_heading(), "headings": list(cur_headings),
"text": t, "tokens": count_tokens(t)})
order += 1
cur_text = ""
cur_headings = []
for heading, _kind, block in blocks:
for piece in _split_oversize(block, chunk_tokens):
cur_tokens = count_tokens(cur_text)
piece_tokens = count_tokens(piece)
last_heading = cur_headings[-1] if cur_headings else heading
crossing = bool(cur_text) and heading != last_heading
over_budget = cur_tokens + piece_tokens > chunk_tokens
# 跨章节合并的条件:要么当前块还太短撑不起一块,要么同属一棵子树且预算够
may_merge = (cur_tokens < min_tokens) or (_same_branch(last_heading, heading)
and not over_budget)
if cur_text and (over_budget or (crossing and not may_merge)):
prev = cur_text
prev_heads = list(cur_headings)
emit()
cur_text = _tail(prev, overlap_tokens)
if cur_text:
cur_text += "\n"
# 带过来的重叠文本属于上一节,heading 沿用它,避免归属错位
cur_headings = prev_heads[-1:]
if heading not in cur_headings:
cur_headings.append(heading)
cur_text += piece + "\n"
emit()
# 收尾:最后一块若过短,并进前一块(常见于文档末尾的一句话小节)
if len(chunks) >= 2 and chunks[-1]["tokens"] < min_tokens:
tail = chunks.pop()
prev = chunks[-1]
prev["text"] = prev["text"] + "\n" + tail["text"]
prev["tokens"] = count_tokens(prev["text"])
for h in tail["headings"]:
if h not in prev["headings"]:
prev["headings"].append(h)
return chunks