74 lines
3.8 KiB
Python
74 lines
3.8 KiB
Python
"""
|
|
FILE: app/core/chunking/chunking_strategies.py
|
|
DESCRIPTION: Implementierung der mathematischen Splitting-Strategien.
|
|
"""
|
|
from typing import List, Dict, Any
|
|
from .chunking_models import RawBlock, Chunk
|
|
from .chunking_utils import estimate_tokens
|
|
from .chunking_parser import split_sentences
|
|
|
|
def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, context_prefix: str = "") -> List[Chunk]:
|
|
"""Fasst Blöcke zusammen und schneidet bei 'target' Tokens."""
|
|
target = config.get("target", 400); max_tokens = config.get("max", 600)
|
|
overlap_val = config.get("overlap", (50, 80))
|
|
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
|
|
chunks = []; buf = []
|
|
|
|
def _add(txt, sec, path):
|
|
idx = len(chunks); win = f"{context_prefix}\n{txt}".strip() if context_prefix else txt
|
|
chunks.append(Chunk(id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx, text=txt, window=win, token_count=estimate_tokens(txt), section_title=sec, section_path=path, neighbors_prev=None, neighbors_next=None))
|
|
|
|
def flush():
|
|
nonlocal buf
|
|
if not buf: return
|
|
text_body = "\n\n".join([b.text for b in buf])
|
|
sec_title = buf[-1].section_title; sec_path = buf[-1].section_path
|
|
if estimate_tokens(text_body) <= max_tokens: _add(text_body, sec_title, sec_path)
|
|
else:
|
|
sents = split_sentences(text_body); cur_sents = []; cur_len = 0
|
|
for s in sents:
|
|
slen = estimate_tokens(s)
|
|
if cur_len + slen > target and cur_sents:
|
|
_add(" ".join(cur_sents), sec_title, sec_path)
|
|
ov_s = []; ov_l = 0
|
|
for os in reversed(cur_sents):
|
|
if ov_l + estimate_tokens(os) < overlap: ov_s.insert(0, os); ov_l += estimate_tokens(os)
|
|
else: break
|
|
cur_sents = list(ov_s); cur_sents.append(s); cur_len = ov_l + slen
|
|
else: cur_sents.append(s); cur_len += slen
|
|
if cur_sents: _add(" ".join(cur_sents), sec_title, sec_path)
|
|
buf = []
|
|
|
|
for b in blocks:
|
|
if b.kind == "heading": continue
|
|
if estimate_tokens("\n\n".join([x.text for x in buf])) + estimate_tokens(b.text) >= target: flush()
|
|
buf.append(b)
|
|
if estimate_tokens(b.text) >= target: flush()
|
|
flush()
|
|
return chunks
|
|
|
|
def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
|
"""Splittet Text basierend auf Markdown-Überschriften."""
|
|
strict = config.get("strict_heading_split", False); target = config.get("target", 400)
|
|
max_tokens = config.get("max", 600); split_level = config.get("split_level", 2)
|
|
chunks = []; buf = []; cur_tokens = 0
|
|
|
|
def _flush(title, path):
|
|
nonlocal buf, cur_tokens
|
|
if not buf: return
|
|
txt = "\n\n".join(buf); win = f"# {doc_title}\n## {title}\n{txt}".strip() if title else txt
|
|
idx = len(chunks)
|
|
chunks.append(Chunk(id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx, text=txt, window=win, token_count=estimate_tokens(txt), section_title=title, section_path=path, neighbors_prev=None, neighbors_next=None))
|
|
buf = []; cur_tokens = 0
|
|
|
|
for b in blocks:
|
|
if b.kind == "heading":
|
|
if b.level < split_level: _flush(b.section_title, b.section_path)
|
|
elif b.level == split_level:
|
|
if strict or cur_tokens >= target: _flush(b.section_title, b.section_path)
|
|
continue
|
|
bt = estimate_tokens(b.text)
|
|
if cur_tokens + bt > max_tokens and buf: _flush(b.section_title, b.section_path)
|
|
buf.append(b.text); cur_tokens += bt
|
|
if buf: _flush(blocks[-1].section_title if blocks else None, blocks[-1].section_path if blocks else "/")
|
|
return chunks |