chunking.py
26.3 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
"""
文档切块(Chunking)核心模块。
负责将解析器输出的结构化块(DocumentBlock)进一步合并、拆分,
生成包含大段逻辑的父级块(Parent Chunk)和适合向量化检索的子级块(Child Chunk),
并维护它们之间的映射与上下文边界关系。
"""
from __future__ import annotations
import uuid
import re
from dataclasses import dataclass, field
from typing import Any
from src.rag.config import CHILD_MAX_CHARS, CHILD_OVERLAP_CHARS, CHILD_TARGET_CHARS, PARENT_MAX_CHARS, PARENT_TARGET_CHARS, TABLE_CHILD_MAX_CHARS, TABLE_CHILD_OVERLAP_ROWS, TABLE_CHILD_TARGET_ROWS
from src.rag.loaders.base import DocumentBlock
from src.rag.metadata import extract_metadata
from src.rag.utils import estimate_tokens, normalize_text, sha256_text
# 经过安全冗余考虑后的实际父块目标长度与最大长度限制
EFFECTIVE_PARENT_TARGET_CHARS = max(PARENT_TARGET_CHARS, 2400)
EFFECTIVE_PARENT_MAX_CHARS = max(PARENT_MAX_CHARS, 3800)
# 文档级 VLM 统计键:只落 rag_documents,不进分片 metadata_json
_DOC_LEVEL_STAT_KEYS = (
"parse_engine", "vlm_page_count", "vlm_total_tokens",
"vlm_input_tokens", "vlm_output_tokens", "vlm_image_tokens", "vlm_duration_ms",
)
@dataclass
class RagChunkData:
"""
表示切分完毕后的一个 RAG 块数据(既可以是 Parent 也可以是 Child)。
包含了用于存储到向量数据库或发送给大模型的各类特征与内容。
"""
chunk_id: str # 块的唯一主键 ID
file_id: str # 归属的文件 ID
parent_chunk_id: str | None # 如果是子块,指向父块 ID;如果本身是父块,则为 None
chunk_level: str # 层级标识:"parent" 或 "child"
chunk_index: int # 在当前文档中的排序索引
content: str # 切分块的实际文本内容
content_hash: str # 文本的 SHA-256 哈希
token_estimate: int # 预估的 Token 消耗数
title_path: str = "" # 块所处的层级标题路径(如:一、产品介绍 / 1.1 价格)
source_name: str = "" # 原始来源文件名
source_path: str = "" # 源文件的磁盘路径
file_type: str = "" # 文件格式扩展名
page_number: int | None = None # 所属的物理页码
slide_number: int | None = None # (如果是PPT)所属的幻灯片页码
sheet_name: str | None = None # (如果是Excel)所属的表单名
row_start: int | None = None # (如果是表格块)起始行号
row_end: int | None = None # (如果是表格块)结束行号
prev_chunk_id: str | None = None# 前一个兄弟块的 ID
next_chunk_id: str | None = None# 后一个兄弟块的 ID
status: str = "active" # 块的可用状态,默认 active
intent_type: str | None = None # 推断的搜索意图类型
page_type: str | None = None # 页面类型标签
brand: str | None = None # 识别出的汽车品牌
business_category: str | None = None # 识别出的一级业务分类
metadata_json: dict[str, Any] = field(default_factory=dict) # 剩余扩展元数据存放的字典
@dataclass
class _ChunkPiece:
content: str
metadata: dict[str, Any] = field(default_factory=dict)
row_start: int | None = None
row_end: int | None = None
def build_chunks(file_id: str, source_name: str, source_path: str, file_type: str, blocks: list[DocumentBlock]) -> tuple[list[RagChunkData], list[RagChunkData]]:
"""
文档切块流水线的总入口:
接收文档解析后的一系列原子块(DocumentBlock),先聚合生成富含长逻辑的父级块(Parents),
接着通过滑动窗口或表格行切分策略,将每个父块分裂出多个子级块(Children),最终建立好链接关系。
:return: (父块列表, 子块列表) 元组
"""
searchable_blocks = [b for b in blocks if b.metadata.get("search_status") != "disabled"]
parents = _build_parent_chunks(file_id, source_name, source_path, file_type, searchable_blocks)
_attach_document_metadata(parents, source_name)
_attach_section_intros(parents)
children: list[RagChunkData] = []
for parent in parents:
children.extend(_split_child_chunks(parent, len(children)))
_link_neighbors(parents)
_link_neighbors(children)
return parents, children
def _attach_document_metadata(parents: list[RagChunkData], source_name: str) -> None:
page_numbers = [parent.page_number for parent in parents if parent.page_number is not None]
document_title = next((parent.title_path for parent in parents if parent.title_path), source_name)
document_title = _section_family(document_title) or source_name
parse_methods = sorted({method for parent in parents for method in parent.metadata_json.get("parse_methods", [])})
for parent in parents:
parent.metadata_json.setdefault("document_title", document_title)
if page_numbers:
parent.metadata_json.setdefault("source_page_count", max(page_numbers))
if parse_methods:
parent.metadata_json.setdefault("parse_methods", parse_methods)
def _build_parent_chunks(file_id: str, source_name: str, source_path: str, file_type: str, blocks: list[DocumentBlock]) -> list[RagChunkData]:
"""
核心:构建父级块列表。
它采用双指针扫描的方法遍历所有的 DocumentBlock,将连续且没有遇到“硬边界”
(如切换了表格、标题或章节)的块合并在一个 Buffer 里,达到长度限制时生成一个 Parent Chunk。
"""
parents: list[RagChunkData] = []
buffer: list[DocumentBlock] = []
current_len = 0
def flush() -> None:
# 将 Buffer 中的块合并为一个大块并清空 Buffer
nonlocal buffer, current_len
if not buffer:
return
content = normalize_text("\n".join(b.text for b in buffer) if _is_table_buffer(buffer) else "\n\n".join(b.text for b in buffer))
if not content or _is_discardable_parent(buffer, content):
buffer = []
current_len = 0
return
anchor = _chunk_anchor_block(buffer)
meta = extract_metadata(content, anchor.title_path, anchor.metadata)
meta.metadata_json.update(_merge_block_metadata(buffer))
# 文档级 VLM 统计只落 rag_documents,不进分片 metadata_json(extract_metadata 会从
# anchor.metadata 把它们带进来,这里统一剥离)
for key in _DOC_LEVEL_STAT_KEYS:
meta.metadata_json.pop(key, None)
title_path = _preferred_title_path(anchor.title_path, meta.metadata_json)
parents.append(
RagChunkData(
chunk_id=f"p_{uuid.uuid4().hex}",
file_id=file_id,
parent_chunk_id=None,
chunk_level="parent",
chunk_index=len(parents),
content=content,
content_hash=sha256_text(content),
token_estimate=estimate_tokens(content),
title_path=title_path,
source_name=source_name,
source_path=source_path,
file_type=file_type,
page_number=anchor.page_number,
slide_number=anchor.slide_number,
sheet_name=anchor.sheet_name,
row_start=_first_value(block.row_start for block in buffer),
row_end=_last_value(block.row_end for block in buffer) or _first_value(block.row_end for block in buffer),
intent_type=meta.intent_type,
page_type=meta.page_type,
brand=meta.brand,
business_category=meta.business_category,
metadata_json=meta.metadata_json,
)
)
buffer = []
current_len = 0
for block in blocks:
text_len = len(block.text)
hard_boundary = _is_hard_boundary(buffer, block)
# 如果长度超出软上限或遇到逻辑分割硬边界,就 flush 一次
if buffer and (current_len + text_len > EFFECTIVE_PARENT_TARGET_CHARS or hard_boundary):
flush()
# 如果单个解析块已经大到超出了硬上限,则直接内部循环强切
if text_len > EFFECTIVE_PARENT_MAX_CHARS:
if block.block_type == "table":
for piece in _split_table_markdown(block.text, EFFECTIVE_PARENT_TARGET_CHARS):
cloned = DocumentBlock(**{**block.__dict__, "text": piece})
buffer = [cloned]
current_len = len(piece)
flush()
continue
else:
for piece in _window_text(block.text, EFFECTIVE_PARENT_TARGET_CHARS, 0):
cloned = DocumentBlock(**{**block.__dict__, "text": piece})
buffer = [cloned]
current_len = len(piece)
flush()
continue
buffer.append(block)
current_len += text_len
flush()
return parents
def _split_child_chunks(parent: RagChunkData, start_index: int) -> list[RagChunkData]:
if _is_table_parent(parent):
pieces = _table_child_pieces(parent)
else:
pieces = _text_child_pieces(parent)
children: list[RagChunkData] = []
for piece in pieces:
content = normalize_text(piece.content)
if not content:
continue
metadata = dict(parent.metadata_json)
metadata.update(piece.metadata)
children.append(
RagChunkData(
**{
**parent.__dict__,
"chunk_id": f"c_{uuid.uuid4().hex}",
"parent_chunk_id": parent.chunk_id,
"chunk_level": "child",
"chunk_index": start_index + len(children),
"content": content,
"content_hash": sha256_text(content),
"token_estimate": estimate_tokens(content),
"row_start": piece.row_start if piece.row_start is not None else parent.row_start,
"row_end": piece.row_end if piece.row_end is not None else parent.row_end,
"prev_chunk_id": None,
"next_chunk_id": None,
"metadata_json": metadata,
}
)
)
return children
def _is_hard_boundary(buffer: list[DocumentBlock], block: DocumentBlock) -> bool:
if not buffer:
return False
last = buffer[-1]
if block.metadata.get("content_role") == "heading" and any(item.metadata.get("content_role") != "heading" for item in buffer):
return True
if block.block_type == "table" and _buffer_can_attach_to_table(buffer, block):
return False
if _paragraph_can_attach_to_previous_table(buffer, block):
return False
if last.block_type != block.block_type:
return True
if last.block_type == "table" and block.block_type == "table":
last_section = _section_family(last.title_path)
curr_section = _section_family(block.title_path)
if last_section and curr_section and last_section != curr_section:
return True
if block.slide_number and last.slide_number and block.slide_number != last.slide_number:
return True
if block.sheet_name and last.sheet_name and block.sheet_name != last.sheet_name:
return True
return False
def _chunk_anchor_block(buffer: list[DocumentBlock]) -> DocumentBlock:
for block in buffer:
if block.block_type in {"table", "table_row"}:
return block
for block in buffer:
if block.metadata.get("content_role") != "heading":
return block
return buffer[-1]
def _is_discardable_parent(buffer: list[DocumentBlock], content: str) -> bool:
if any(block.block_type in {"table", "table_row"} for block in buffer):
return False
if len(content) >= 80:
return False
return all(block.metadata.get("content_role") == "heading" for block in buffer)
def _buffer_can_attach_to_table(buffer: list[DocumentBlock], table: DocumentBlock) -> bool:
if any(block.block_type in {"table", "table_row"} for block in buffer):
return False
if sum(len(block.text) for block in buffer) > 700:
return False
buffer_section = _section_family(_chunk_anchor_block(buffer).title_path)
table_section = _section_family(table.title_path)
return not buffer_section or not table_section or buffer_section == table_section or table_section.startswith(buffer_section)
def _paragraph_can_attach_to_previous_table(buffer: list[DocumentBlock], block: DocumentBlock) -> bool:
if block.block_type != "paragraph" or block.metadata.get("content_role") == "heading":
return False
if not buffer or buffer[-1].block_type not in {"table", "table_row"}:
return False
if len(block.text) > 400:
return False
return _section_family(buffer[-1].title_path) == _section_family(block.title_path)
def _is_table_buffer(buffer: list[DocumentBlock]) -> bool:
return any(block.block_type in {"table", "table_row"} for block in buffer)
def _first_value(values) -> Any:
return next((value for value in values if value is not None), None)
def _last_value(values) -> Any:
result = None
for value in values:
if value is not None:
result = value
return result
def _merge_block_metadata(buffer: list[DocumentBlock]) -> dict[str, Any]:
if not buffer:
return {}
anchor = _chunk_anchor_block(buffer)
merged = dict(anchor.metadata or {})
parse_methods: list[str] = []
block_types: list[str] = []
section_paths: list[list[str]] = []
table_headers: list[str] = []
table_ids: list[str] = []
page_numbers = [block.page_number for block in buffer if block.page_number is not None]
for block in buffer:
parse_method = block.metadata.get("parse_method")
if parse_method and parse_method not in parse_methods:
parse_methods.append(parse_method)
if block.block_type not in block_types:
block_types.append(block.block_type)
section_path = block.metadata.get("section_path")
if isinstance(section_path, list) and section_path not in section_paths:
section_paths.append(section_path)
table_header = block.metadata.get("table_header")
if table_header and table_header not in table_headers:
table_headers.append(table_header)
table_id = block.metadata.get("table_id")
if table_id and table_id not in table_ids:
table_ids.append(table_id)
# Remove verbose internal debug fields + 文档级 VLM 统计(落库在 rag_documents,不进分片)
for key in ("block_offsets", "bbox_union", "bbox", "text_quality", "document_parse_methods",
"numeric_facts", "font_size", "is_bold", "_page_font_stats",
"parse_engine", "vlm_page_count", "vlm_total_tokens",
"vlm_input_tokens", "vlm_output_tokens", "vlm_image_tokens", "vlm_duration_ms"):
merged.pop(key, None)
if parse_methods:
merged["parse_methods"] = parse_methods
if block_types:
merged["block_types"] = block_types
if page_numbers:
merged["page_start"] = min(page_numbers)
merged["page_end"] = max(page_numbers)
if section_paths:
section_path = _best_section_path(section_paths)
merged["section_path"] = section_path
merged["section_title"] = section_path[-1] if section_path else None
if table_headers:
merged["table_headers"] = table_headers
merged["table_header"] = table_headers[0]
if table_ids:
merged["table_ids"] = table_ids
if _is_table_buffer(buffer):
table_blocks = [block for block in buffer if block.block_type in {"table", "table_row"}]
merged["row_start"] = _first_value(block.row_start for block in table_blocks)
merged["row_end"] = _last_value(block.row_end for block in table_blocks)
merged["chunking_strategy"] = "table_rows"
merged["content_kind"] = "mixed_table" if any(block.block_type == "paragraph" for block in buffer) else "table"
else:
merged["chunking_strategy"] = "text_window"
merged["content_kind"] = "text"
return merged
def _best_section_path(paths: list[list[str]]) -> list[str]:
if not paths:
return []
best = paths[0]
for path in paths[1:]:
if len(path) > len(best):
best = path
elif len(path) == len(best) and len(" / ".join(path)) > len(" / ".join(best)):
best = path
return best
def _infer_special_section_path(text: str, existing_paths: list[list[str]]) -> list[str] | None:
return None
def _preferred_title_path(anchor_title_path: str, metadata: dict[str, Any]) -> str:
section_path = metadata.get("section_path")
if not isinstance(section_path, list) or not section_path:
return anchor_title_path
section_title_path = " / ".join(str(item) for item in section_path if str(item).strip())
if not section_title_path:
return anchor_title_path
suffix = ""
base_title = anchor_title_path or ""
if " / P" in base_title:
base_title, suffix_tail = base_title.split(" / P", 1)
suffix = f" / P{suffix_tail}"
if not base_title or section_title_path.startswith(base_title) or section_path[-1] not in base_title:
return f"{section_title_path}{suffix}"
return anchor_title_path
def _attach_section_intros(parents: list[RagChunkData]) -> None:
last_intro_by_section: dict[str, str] = {}
for parent in parents:
section_key = _section_family(parent.title_path)
if not section_key:
continue
if _is_table_parent(parent):
section_intro = last_intro_by_section.get(section_key)
if section_intro:
parent.metadata_json["section_intro"] = section_intro
continue
if _looks_like_section_intro(parent):
last_intro_by_section[section_key] = parent.content
def _looks_like_section_intro(parent: RagChunkData) -> bool:
text = parent.content.strip()
if not text or len(text) > 400:
return False
if text == parent.title_path:
return False
return bool("说明" in text or re_chapter_heading(text) or any(word in text for word in ("活动价", "仅提供", "适用于", "享有")))
def _section_family(title_path: str) -> str:
return title_path.split(" / P", 1)[0].strip()
def re_chapter_heading(text: str) -> bool:
return bool(re.search(r"(^|\n)[一二三四五六七八九十]+、", text))
def _is_table_parent(parent: RagChunkData) -> bool:
return bool(
parent.metadata_json.get("table_markdown")
or "table" in (parent.metadata_json.get("block_types") or [])
)
def _text_child_pieces(parent: RagChunkData) -> list[_ChunkPiece]:
windows = _window_text_with_offsets(parent.content, CHILD_TARGET_CHARS, CHILD_OVERLAP_CHARS)
pieces: list[_ChunkPiece] = []
for idx, (text, start, end) in enumerate(windows):
overlap_prev = min(CHILD_OVERLAP_CHARS, start) if idx else 0
overlap_next = min(CHILD_OVERLAP_CHARS, max(0, len(parent.content) - end)) if end < len(parent.content) else 0
pieces.append(
_ChunkPiece(
content=normalize_text(text),
metadata={
"chunking_strategy": "text_window",
"char_start": start,
"char_end": end,
"overlap_prev_chars": overlap_prev,
"overlap_next_chars": overlap_next,
},
)
)
return pieces
def _split_table_segments(
lines: list[str],
) -> tuple[list[tuple[list[str], list[str]]], list[str]]:
"""将内容行按连续 | 行切割为若干 (prefix_text, table_rows) 段。
返回 (segments, trailing_text),trailing_text 是最后一段 | 行之后的文字行。
"""
segments: list[tuple[list[str], list[str]]] = []
cur_text: list[str] = []
cur_table: list[str] = []
in_table = False
for line in lines:
if line.startswith("|"):
in_table = True
cur_table.append(line)
else:
if in_table:
segments.append((cur_text[:], cur_table[:]))
cur_text = [line]
cur_table = []
in_table = False
else:
cur_text.append(line)
if in_table:
segments.append((cur_text, cur_table))
trailing: list[str] = []
else:
trailing = cur_text
return segments, trailing
def _table_child_pieces(parent: RagChunkData) -> list[_ChunkPiece]:
content = parent.content
all_lines = [line.strip() for line in content.splitlines() if line.strip()]
segments, trailing = _split_table_segments(all_lines)
if not segments:
return _text_child_pieces(parent)
all_pieces: list[_ChunkPiece] = []
row_cursor = parent.row_start or 1
for seg_idx, (prefix, table_rows) in enumerate(segments):
if not table_rows:
continue
is_last_seg = seg_idx == len(segments) - 1
seg_trailing = trailing if is_last_seg else []
if len(table_rows) > 1 and "---" in table_rows[1].replace(" ", "").replace("|", ""):
header = table_rows[:2]
rows = table_rows[2:]
else:
header = []
rows = table_rows
if len(table_rows) <= 6:
piece_lines = [*prefix, *table_rows, *seg_trailing]
all_pieces.append(
_ChunkPiece(
content=normalize_text("\n".join(piece_lines)) if piece_lines else content,
metadata={
"chunking_strategy": "table_rows",
"overlap_prev_rows": 0,
"overlap_next_rows": 0,
"table_header": _markdown_table_header(table_rows),
"table_context_lines": prefix,
},
row_start=row_cursor,
row_end=row_cursor + max(0, len(rows) - 1),
)
)
row_cursor += max(1, len(rows))
continue
step = max(1, TABLE_CHILD_TARGET_ROWS - TABLE_CHILD_OVERLAP_ROWS)
for start in range(0, len(rows), step):
group: list[str] = []
current_len = sum(len(l) for l in [*prefix, *header])
for row in rows[start:]:
if group and (
len(group) >= TABLE_CHILD_TARGET_ROWS
or current_len + len(row) > TABLE_CHILD_MAX_CHARS
):
break
group.append(row)
current_len += len(row)
if not group:
continue
is_last_piece = start + len(group) >= len(rows)
row_start_val = row_cursor + start
row_end_val = row_start_val + len(group) - 1
overlap_prev = min(TABLE_CHILD_OVERLAP_ROWS, start)
overlap_next = min(TABLE_CHILD_OVERLAP_ROWS, max(0, len(rows) - (start + len(group))))
lines_for_piece = [*prefix, *header, *group]
if is_last_piece and is_last_seg and seg_trailing:
lines_for_piece = [*lines_for_piece, *seg_trailing]
all_pieces.append(
_ChunkPiece(
content=normalize_text("\n".join(lines_for_piece)),
metadata={
"chunking_strategy": "table_rows",
"table_header": _markdown_table_header(header or table_rows),
"table_context_lines": prefix,
"overlap_prev_rows": overlap_prev,
"overlap_next_rows": overlap_next,
},
row_start=row_start_val,
row_end=row_end_val,
)
)
row_cursor += max(1, len(rows))
return all_pieces or [_ChunkPiece(content=content, row_start=parent.row_start, row_end=parent.row_end)]
def _markdown_table_header(lines: list[str]) -> str:
for line in lines:
if line.strip().startswith("|") and "---" not in line.replace(" ", "").replace("|", ""):
return line.strip()
return ""
def _split_table_markdown(markdown: str, target_chars: int) -> list[str]:
lines = [line.strip() for line in markdown.splitlines() if line.strip()]
if len(lines) <= 2:
return [markdown]
if len(lines) > 1 and "---" in lines[1].replace(" ", "").replace("|", ""):
header = lines[:2]
rows = lines[2:]
else:
header = []
rows = lines
pieces: list[str] = []
group: list[str] = []
current_len = sum(len(h) for h in header)
for row in rows:
if group and current_len + len(row) > target_chars:
pieces.append(normalize_text("\n".join([*header, *group])))
group = []
current_len = sum(len(h) for h in header)
group.append(row)
current_len += len(row)
if group:
pieces.append(normalize_text("\n".join([*header, *group])))
return pieces or [markdown]
def _window_text(text: str, target: int, overlap: int) -> list[str]:
return [piece for piece, _, _ in _window_text_with_offsets(text, target, overlap)]
def _window_text_with_offsets(text: str, target: int, overlap: int) -> list[tuple[str, int, int]]:
text = normalize_text(text)
if len(text) <= target:
return [(text, 0, len(text))]
pieces: list[tuple[str, int, int]] = []
start = 0
max_len = max(target, CHILD_MAX_CHARS if target <= CHILD_TARGET_CHARS else PARENT_MAX_CHARS)
while start < len(text):
end = min(len(text), start + max_len)
if end < len(text):
split_at = max(
text.rfind("\n", start, end),
text.rfind("。", start, end),
text.rfind(";", start, end),
text.rfind(",", start, end),
)
if split_at > start + int(target * 0.45):
end = split_at + 1
pieces.append((text[start:end], start, end))
if end >= len(text):
break
start = max(0, end - overlap)
return pieces
def _link_neighbors(chunks: list[RagChunkData]) -> None:
for idx, chunk in enumerate(chunks):
chunk.prev_chunk_id = chunks[idx - 1].chunk_id if idx > 0 else None
chunk.next_chunk_id = chunks[idx + 1].chunk_id if idx + 1 < len(chunks) else None