184 lines
7.9 KiB
Python
184 lines
7.9 KiB
Python
"""
|
|
FILE: app/core/chunking/chunking_strategies.py
|
|
DESCRIPTION: Strategien für atomares Sektions-Chunking v3.3.6.
|
|
AUDIT: 100% Konformität zur 'by_heading' Spezifikation.
|
|
- Block-Aware Flushing: Trennung nur an Blockgrenzen.
|
|
- Atomic Section Vorausschau: Verhindert Sektions-Zerreißung.
|
|
"""
|
|
import math
|
|
from typing import List, Dict, Any, Optional
|
|
from .chunking_models import RawBlock, Chunk
|
|
from .chunking_parser import split_sentences
|
|
|
|
def _safe_estimate_tokens(text: str) -> int:
|
|
"""Konservative Token-Schätzung für deutschen Text (len/3 statt len/4)."""
|
|
return max(1, math.ceil(len(text.strip()) / 3))
|
|
|
|
def _create_context_win(doc_title: str, sec_title: Optional[str], text: str) -> str:
|
|
"""Baut den Breadcrumb-Kontext für das Embedding-Fenster."""
|
|
parts = []
|
|
if doc_title: parts.append(doc_title)
|
|
if sec_title and sec_title != doc_title: parts.append(sec_title)
|
|
prefix = " > ".join(parts)
|
|
return f"{prefix}\n{text}".strip() if prefix else text
|
|
|
|
def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
|
"""
|
|
Gruppiert Blöcke zu Sektionen und hält diese atomar zusammen.
|
|
Nutzt Block-Aware-Flushing, um Sektionsgrenzen strikt zu wahren.
|
|
"""
|
|
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)
|
|
overlap_cfg = config.get("overlap", (50, 80))
|
|
overlap = sum(overlap_cfg) // 2 if isinstance(overlap_cfg, (list, tuple)) else overlap_cfg
|
|
|
|
chunks: List[Chunk] = []
|
|
buf: List[RawBlock] = []
|
|
|
|
def _add_chunk(txt, title, path):
|
|
idx = len(chunks)
|
|
win = _create_context_win(doc_title, title, txt)
|
|
chunks.append(Chunk(
|
|
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
|
text=txt, window=win, token_count=_safe_estimate_tokens(txt),
|
|
section_title=title, section_path=path,
|
|
neighbors_prev=None, neighbors_next=None
|
|
))
|
|
|
|
def _flush_buffer():
|
|
nonlocal buf
|
|
if not buf: return
|
|
|
|
# Block-Aware Processing innerhalb des Puffers
|
|
current_blocks = []
|
|
current_len = 0
|
|
|
|
for b in buf:
|
|
b_len = _safe_estimate_tokens(b.text)
|
|
|
|
# Falls dieser Block den aktuellen Chunk sprengen würde -> Vorher abschließen
|
|
if current_len + b_len > max_tokens and current_blocks:
|
|
txt = "\n\n".join([cb.text for cb in current_blocks])
|
|
_add_chunk(txt, current_blocks[0].section_title, current_blocks[0].section_path)
|
|
current_blocks = []
|
|
current_len = 0
|
|
|
|
# Falls ein einzelner Block alleine zu groß ist (Sliding Window Fallback)
|
|
if b_len > max_tokens:
|
|
if current_blocks: # Vorherigen Rest wegschreiben
|
|
txt = "\n\n".join([cb.text for cb in current_blocks])
|
|
_add_chunk(txt, current_blocks[0].section_title, current_blocks[0].section_path)
|
|
current_blocks = []
|
|
current_len = 0
|
|
|
|
# Sätze dieses einen Riesen-Blocks splitten
|
|
sents = split_sentences(b.text)
|
|
cur_sents = []; sub_len = 0
|
|
header_text = b.text if b.kind == "heading" else ""
|
|
|
|
for s in sents:
|
|
slen = _safe_estimate_tokens(s)
|
|
if sub_len + slen > target and cur_sents:
|
|
_add_chunk(" ".join(cur_sents), b.section_title, b.section_path)
|
|
# Overlap-Erzeugung & Header-Wiederholung
|
|
ov_s = [header_text] if header_text else []
|
|
ov_l = _safe_estimate_tokens(header_text) if header_text else 0
|
|
for os in reversed(cur_sents):
|
|
if os == header_text: continue
|
|
t_len = _safe_estimate_tokens(os)
|
|
if ov_l + t_len < overlap:
|
|
ov_s.insert(len(ov_s)-1 if header_text else 0, os)
|
|
ov_l += t_len
|
|
else: break
|
|
cur_sents = list(ov_s); cur_sents.append(s); sub_len = ov_l + slen
|
|
else: cur_sents.append(s); sub_len += slen
|
|
if cur_sents:
|
|
_add_chunk(" ".join(cur_sents), b.section_title, b.section_path)
|
|
else:
|
|
current_blocks.append(b)
|
|
current_len += b_len
|
|
|
|
# Den verbleibenden Rest im Puffer als finalen Chunk schreiben
|
|
if current_blocks:
|
|
txt = "\n\n".join([cb.text for cb in current_blocks])
|
|
_add_chunk(txt, current_blocks[0].section_title, current_blocks[0].section_path)
|
|
|
|
buf = []
|
|
|
|
# SCHRITT 1: Gruppierung in atomare Sektions-Einheiten
|
|
sections: List[List[RawBlock]] = []
|
|
curr_sec: List[RawBlock] = []
|
|
|
|
for b in blocks:
|
|
if b.kind == "heading" and b.level <= split_level:
|
|
if curr_sec: sections.append(curr_sec)
|
|
curr_sec = [b]
|
|
else:
|
|
curr_sec.append(b)
|
|
if curr_sec: sections.append(curr_sec)
|
|
|
|
# SCHRITT 2: Verarbeitung der Sektionen mit Look-Ahead
|
|
for sec in sections:
|
|
sec_text = "\n\n".join([b.text for b in sec])
|
|
sec_tokens = _safe_estimate_tokens(sec_text)
|
|
|
|
# Aktueller Füllstand des Puffers
|
|
cur_buf_tokens = sum(_safe_estimate_tokens(b.text) for b in buf)
|
|
|
|
if buf:
|
|
# PRÜFUNG: Wenn die neue Sektion den Puffer über das Limit treibt
|
|
# ODER wenn der Puffer bereits das Ziel-Format erreicht hat
|
|
if (cur_buf_tokens + sec_tokens > max_tokens) or (cur_buf_tokens >= target):
|
|
_flush_buffer()
|
|
# PRÜFUNG: Strikter Split an Überschriften
|
|
elif strict and sec[0].kind == "heading" and sec[0].level == split_level:
|
|
_flush_buffer()
|
|
|
|
buf.extend(sec)
|
|
|
|
# Falls eine Riesen-Sektion hinzugefügt wurde, die sofort raus muss
|
|
if sum(_safe_estimate_tokens(b.text) for b in buf) >= max_tokens:
|
|
_flush_buffer()
|
|
|
|
_flush_buffer()
|
|
return chunks
|
|
|
|
def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, context_prefix: str = "") -> List[Chunk]:
|
|
"""Basis-Sliding-Window für flache Texte ohne Sektionsfokus."""
|
|
target = config.get("target", 400)
|
|
max_tokens = config.get("max", 600)
|
|
|
|
chunks: List[Chunk] = []
|
|
buf: List[RawBlock] = []
|
|
|
|
for b in blocks:
|
|
b_tokens = _safe_estimate_tokens(b.text)
|
|
current_tokens = sum(_safe_estimate_tokens(x.text) for x in buf) if buf else 0
|
|
|
|
if current_tokens + b_tokens > max_tokens and buf:
|
|
txt = "\n\n".join([x.text for x in buf])
|
|
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=current_tokens,
|
|
section_title=buf[0].section_title, section_path=buf[0].section_path,
|
|
neighbors_prev=None, neighbors_next=None))
|
|
buf = []
|
|
current_tokens = 0
|
|
|
|
buf.append(b)
|
|
|
|
if buf:
|
|
txt = "\n\n".join([x.text for x in buf])
|
|
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=_safe_estimate_tokens(txt),
|
|
section_title=buf[0].section_title, section_path=buf[0].section_path,
|
|
neighbors_prev=None, neighbors_next=None))
|
|
|
|
return chunks |