Aktualisierung der atomaren Sektions-Chunking-Strategie auf Version 3.9.8 mit verbesserten Implementierungen des 'Pack-and-Carry-Over' Verfahrens. Einführung von Look-Ahead zur strikten Einhaltung von Sektionsgrenzen und Vermeidung redundanter Kanten-Injektionen. Anpassungen an der Chunk-Erstellung und Optimierung der Handhabung von leeren Überschriften.

This commit is contained in:
Lars committed 2025-12-30 07:54:54 +01:00
1 parent 06fc42ed37
commit 65d697b7be
2 files changed
+32 -20

No files matched your search

+17 -14
View File
@@ -1,11 +1,9 @@
"""
FILE: app/core/chunking/chunking_strategies.py
DESCRIPTION: Strategien für atomares Sektions-Chunking v3.9.6.
Implementiert das 'Pack-and-Carry-Over' Verfahren:
1. Packt ganze Abschnitte basierend auf Schätzung.
2. Kein physischer Overflow-Check während des Packens.
3. Smart-Zerlegung von Übergrößen mit Carry-Over in die Queue.
- Hard-Split-Logik für strict_heading_split integriert.
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
@@ -13,6 +11,7 @@ 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)
@@ -33,6 +32,7 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
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(
@@ -54,7 +54,6 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
})
curr_blocks = [b]
else:
curr_sec_has_content = True
curr_blocks.append(b)
if curr_blocks:
sections.append({
@@ -75,26 +74,27 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
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 (H1 vor H2) werden mit dem nächsten Item verschmolzen
# 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 das Verschmelzen das Limit gesprengt würde, flashen wir vorher
# 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 nicht-leeren Sektion geflasht
# Im Hard-Split wird nach jeder Sektion geflasht
_emit(current_chunk_text, current_meta["title"], current_meta["path"])
current_chunk_text = ""
continue
@@ -104,7 +104,7 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
combined_est = estimate_tokens(combined_text)
if combined_est <= max_tokens:
# Regel 1 & 2: Passt rein -> Aufnehmen
# Regel 1 & 2: Passt rein laut Schätzung -> Aufnehmen
current_chunk_text = combined_text
else:
if current_chunk_text:
@@ -119,8 +119,7 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
take_sents = []; take_len = 0
while sents:
s = sents.pop(0)
slen = estimate_tokens(s)
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
@@ -129,6 +128,7 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
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
@@ -140,9 +140,10 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
return chunks
def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
"""Basis-Sliding-Window für flache Texte."""
"""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
@@ -152,8 +153,10 @@ def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note
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