162 lines
7.4 KiB
Python
162 lines
7.4 KiB
Python
"""
|
|
FILE: app/core/chunking/chunking_strategies.py
|
|
DESCRIPTION: Strategien für atomares Sektions-Chunking v3.9.8.
|
|
Implementiert das 'Pack-and-Carry-Over' Verfahren nach Regel 1-3.
|
|
- Keine redundante Kanten-Injektion.
|
|
- Strikte Einhaltung von Sektionsgrenzen via Look-Ahead.
|
|
"""
|
|
from typing import List, Dict, Any, Optional
|
|
from .chunking_models import RawBlock, Chunk
|
|
from .chunking_utils import estimate_tokens
|
|
from .chunking_parser import split_sentences
|
|
|
|
def _create_win(doc_title: str, sec_title: Optional[str], text: str) -> str:
|
|
"""Baut den Breadcrumb-Kontext für das Embedding-Fenster."""
|
|
parts = [doc_title] if doc_title else []
|
|
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]:
|
|
"""
|
|
Universelle Heading-Strategie mit Carry-Over Logik.
|
|
"""
|
|
smart_edge = config.get("enable_smart_edge_allocation", True)
|
|
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] = []
|
|
|
|
def _emit(txt, title, path):
|
|
"""Schreibt den finalen Chunk ohne Text-Modifikationen."""
|
|
idx = len(chunks)
|
|
win = _create_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=estimate_tokens(txt),
|
|
section_title=title, section_path=path, neighbors_prev=None, neighbors_next=None
|
|
))
|
|
|
|
# --- SCHRITT 1: Gruppierung in atomare Sektions-Einheiten ---
|
|
sections: List[Dict[str, Any]] = []
|
|
curr_blocks = []
|
|
for b in blocks:
|
|
if b.kind == "heading" and b.level <= split_level:
|
|
if curr_blocks:
|
|
sections.append({
|
|
"text": "\n\n".join([x.text for x in curr_blocks]),
|
|
"meta": curr_blocks[0],
|
|
"is_empty": len(curr_blocks) == 1 and curr_blocks[0].kind == "heading"
|
|
})
|
|
curr_blocks = [b]
|
|
else:
|
|
curr_blocks.append(b)
|
|
if curr_blocks:
|
|
sections.append({
|
|
"text": "\n\n".join([x.text for x in curr_blocks]),
|
|
"meta": curr_blocks[0],
|
|
"is_empty": len(curr_blocks) == 1 and curr_blocks[0].kind == "heading"
|
|
})
|
|
|
|
# --- SCHRITT 2: Verarbeitung der Queue ---
|
|
queue = list(sections)
|
|
current_chunk_text = ""
|
|
current_meta = {"title": None, "path": "/"}
|
|
|
|
# Bestimmung des Modus: Hard-Split wenn smart_edge=False ODER strict=True
|
|
is_hard_split_mode = (not smart_edge) or (strict)
|
|
|
|
while queue:
|
|
item = queue.pop(0)
|
|
item_text = item["text"]
|
|
|
|
# Initialisierung für neuen Chunk
|
|
if not current_chunk_text:
|
|
current_meta["title"] = item["meta"].section_title
|
|
current_meta["path"] = item["meta"].section_path
|
|
|
|
# FALL A: HARD SPLIT MODUS
|
|
if is_hard_split_mode:
|
|
# Leere Überschriften (z.B. H1 direkt vor H2) verbleiben am nächsten Chunk
|
|
if item.get("is_empty", False) and queue:
|
|
current_chunk_text = (current_chunk_text + "\n\n" + item_text).strip()
|
|
continue
|
|
|
|
combined = (current_chunk_text + "\n\n" + item_text).strip()
|
|
# Wenn durch Verschmelzung das Limit gesprengt würde, vorher flashen
|
|
if estimate_tokens(combined) > max_tokens and current_chunk_text:
|
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
|
current_chunk_text = item_text
|
|
else:
|
|
current_chunk_text = combined
|
|
|
|
# Im Hard-Split wird nach jeder Sektion geflasht
|
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
|
current_chunk_text = ""
|
|
continue
|
|
|
|
# FALL B: SMART MODE (Regel 1-3)
|
|
combined_text = (current_chunk_text + "\n\n" + item_text).strip() if current_chunk_text else item_text
|
|
combined_est = estimate_tokens(combined_text)
|
|
|
|
if combined_est <= max_tokens:
|
|
# Regel 1 & 2: Passt rein laut Schätzung -> Aufnehmen
|
|
current_chunk_text = combined_text
|
|
else:
|
|
if current_chunk_text:
|
|
# Regel 2: Flashen an Sektionsgrenze, Item zurücklegen
|
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
|
current_chunk_text = ""
|
|
queue.insert(0, item)
|
|
else:
|
|
# Regel 3: Einzelne Sektion zu groß -> Smart Zerlegung
|
|
sents = split_sentences(item_text)
|
|
header_prefix = item["meta"].text if item["meta"].kind == "heading" else ""
|
|
|
|
take_sents = []; take_len = 0
|
|
while sents:
|
|
s = sents.pop(0); slen = estimate_tokens(s)
|
|
if take_len + slen > target and take_sents:
|
|
sents.insert(0, s); break
|
|
take_sents.append(s); take_len += slen
|
|
|
|
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"])
|
|
|
|
if sents:
|
|
remainder = " ".join(sents)
|
|
# Kontext-Erhalt: Überschrift für den Rest wiederholen
|
|
if header_prefix and not remainder.startswith(header_prefix):
|
|
remainder = header_prefix + "\n\n" + remainder
|
|
# Carry-Over: Rest wird vorne in die Queue geschoben
|
|
queue.insert(0, {"text": remainder, "meta": item["meta"], "is_split": True})
|
|
|
|
if current_chunk_text:
|
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
|
|
|
|
return chunks
|
|
|
|
def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
|
"""Standard-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 = estimate_tokens(b.text)
|
|
curr_tokens = sum(estimate_tokens(x.text) for x in buf) if buf else 0
|
|
if curr_tokens + b_tokens > max_tokens and buf:
|
|
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
|
|
win = _create_win(doc_title, buf[0].section_title, txt)
|
|
chunks.append(Chunk(id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx, text=txt, window=win, token_count=curr_tokens, section_title=buf[0].section_title, section_path=buf[0].section_path, neighbors_prev=None, neighbors_next=None))
|
|
buf = []
|
|
buf.append(b)
|
|
|
|
if buf:
|
|
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
|
|
win = _create_win(doc_title, buf[0].section_title, 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=buf[0].section_title, section_path=buf[0].section_path, neighbors_prev=None, neighbors_next=None))
|
|
|
|
return chunks |