- Added a new function `_propagate_section_type_backwards` to ensure that the section_type is correctly assigned to all blocks within a heading section, even if the [!section] callout appears later in the text. - Updated the `parse_blocks` function to call this new method, enhancing the accuracy of section-type assignments. - Modified chunking strategies to reflect the changes in section-type handling, simplifying logic related to section-type transitions. - Expanded unit tests to validate the backward propagation of section_type, ensuring comprehensive coverage of the new functionality.
295 lines
14 KiB
Python
295 lines
14 KiB
Python
"""
|
|
FILE: app/core/chunking/chunking_strategies.py
|
|
DESCRIPTION: Strategien für atomares Sektions-Chunking v3.9.9.
|
|
Implementiert das 'Pack-and-Carry-Over' Verfahren nach Regel 1-3.
|
|
- Keine redundante Kanten-Injektion.
|
|
- Strikte Einhaltung von Sektionsgrenzen via Look-Ahead.
|
|
- Fix: Synchronisierung der Parameter mit dem Orchestrator (context_prefix).
|
|
WP-24c v4.2.5: Strict-Mode ohne Carry-Over - Bei strict_heading_split wird nach jeder Sektion geflasht.
|
|
WP-26 v1.0: section_type und block_id werden an Chunks weitergegeben.
|
|
WP-26 v1.1: Section-Type-Wechsel erzwingt IMMER einen neuen Chunk (unabhängig vom Profil).
|
|
WP-26 v1.3: Parser propagiert section_type rückwirkend für Heading-Sektionen.
|
|
Der [!section] Callout kann irgendwo im Abschnitt stehen.
|
|
Alle Blöcke einer Heading-Sektion haben den korrekten section_type.
|
|
"""
|
|
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(context_prefix: str, sec_title: Optional[str], text: str) -> str:
|
|
"""Baut den Breadcrumb-Kontext für das Embedding-Fenster."""
|
|
parts = [context_prefix] if context_prefix else []
|
|
# Verhindert Dopplung, falls der Context-Prefix (H1) bereits den Sektionsnamen enthält
|
|
if sec_title and f"# {sec_title}" != context_prefix and sec_title not in (context_prefix or ""):
|
|
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, context_prefix: str = "") -> List[Chunk]:
|
|
"""
|
|
Universelle Heading-Strategie mit Carry-Over Logik.
|
|
Synchronisiert auf context_prefix für Kompatibilität mit dem Orchestrator.
|
|
"""
|
|
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, section_type=None, block_id=None):
|
|
"""
|
|
Schreibt den finalen Chunk ohne Text-Modifikationen.
|
|
WP-26 v1.0: Erweitert um section_type und block_id.
|
|
"""
|
|
idx = len(chunks)
|
|
win = _create_win(context_prefix, 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,
|
|
section_type=section_type, block_id=block_id
|
|
))
|
|
|
|
# --- SCHRITT 1: Gruppierung in atomare Sektions-Einheiten ---
|
|
# WP-26 v1.3: Der Parser propagiert section_type bereits rückwirkend für Heading-Sektionen.
|
|
# Alle Blöcke einer Heading-Sektion (inkl. Heading selbst) haben bereits den korrekten section_type.
|
|
sections: List[Dict[str, Any]] = []
|
|
curr_blocks = []
|
|
|
|
def _flush_section():
|
|
"""Hilfsfunktion zum Abschließen einer Sektion."""
|
|
nonlocal curr_blocks
|
|
if not curr_blocks:
|
|
return
|
|
# WP-26 v1.3: section_type wird vom Parser bereits korrekt gesetzt (rückwirkend)
|
|
# Alle Blöcke einer Heading-Sektion haben denselben section_type
|
|
effective_section_type = next((cb.section_type for cb in curr_blocks if cb.section_type), None)
|
|
effective_block_id = next((cb.block_id for cb in curr_blocks if cb.block_id), None)
|
|
|
|
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",
|
|
"section_type": effective_section_type,
|
|
"block_id": effective_block_id
|
|
})
|
|
curr_blocks = []
|
|
|
|
for b in blocks:
|
|
if b.kind == "heading" and b.level <= split_level:
|
|
# Heading-basierter Split
|
|
_flush_section()
|
|
curr_blocks = [b]
|
|
else:
|
|
curr_blocks.append(b)
|
|
|
|
_flush_section()
|
|
|
|
# --- SCHRITT 2: Verarbeitung der Queue ---
|
|
queue = list(sections)
|
|
current_chunk_text = ""
|
|
# WP-26 v1.0: Erweitert um section_type und block_id
|
|
current_meta = {"title": None, "path": "/", "section_type": None, "block_id": None}
|
|
|
|
# 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
|
|
# WP-26 v1.0: section_type und block_id aus Item übernehmen
|
|
current_meta["section_type"] = item.get("section_type")
|
|
current_meta["block_id"] = item.get("block_id")
|
|
|
|
# FALL A: HARD SPLIT MODUS (WP-24c v4.2.5: Strict-Mode ohne Carry-Over)
|
|
if is_hard_split_mode:
|
|
# WP-24c v4.2.5: Bei strict_heading_split: true wird nach JEDER Sektion geflasht
|
|
# Kein Carry-Over erlaubt, auch nicht für leere Überschriften
|
|
if current_chunk_text:
|
|
# Flashe vorherigen Chunk
|
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"],
|
|
current_meta["section_type"], current_meta["block_id"])
|
|
current_chunk_text = ""
|
|
|
|
# Neue Sektion: Initialisiere Meta
|
|
current_meta["title"] = item["meta"].section_title
|
|
current_meta["path"] = item["meta"].section_path
|
|
# WP-26 v1.0: section_type und block_id aus Item übernehmen
|
|
current_meta["section_type"] = item.get("section_type")
|
|
current_meta["block_id"] = item.get("block_id")
|
|
|
|
# WP-24c v4.2.5: Auch leere Sektionen werden als separater Chunk erstellt
|
|
# (nur Überschrift, kein Inhalt)
|
|
if item.get("is_empty", False):
|
|
# Leere Sektion: Nur Überschrift als Chunk
|
|
_emit(item_text, current_meta["title"], current_meta["path"],
|
|
current_meta["section_type"], current_meta["block_id"])
|
|
else:
|
|
# Normale Sektion: Prüfe auf Token-Limit
|
|
if estimate_tokens(item_text) > max_tokens:
|
|
# Sektion zu groß: Smart Zerlegung (aber trotzdem in separaten Chunks)
|
|
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:
|
|
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"],
|
|
current_meta["section_type"], current_meta["block_id"])
|
|
take_sents = [s]; take_len = slen
|
|
else:
|
|
take_sents.append(s); take_len += slen
|
|
|
|
if take_sents:
|
|
_emit(" ".join(take_sents), current_meta["title"], current_meta["path"],
|
|
current_meta["section_type"], current_meta["block_id"])
|
|
else:
|
|
# Sektion passt: Direkt als Chunk
|
|
_emit(item_text, current_meta["title"], current_meta["path"],
|
|
current_meta["section_type"], current_meta["block_id"])
|
|
|
|
current_chunk_text = ""
|
|
continue
|
|
|
|
# FALL B: SMART MODE (Regel 1-3)
|
|
# WP-26 v1.1: Prüfe auf Section-Type-Wechsel AUCH in Schritt 2
|
|
# Wenn sich der section_type zwischen current_meta und item ändert, muss gesplittet werden
|
|
item_section_type = item.get("section_type")
|
|
current_section_type_meta = current_meta.get("section_type")
|
|
|
|
# Section-Type-Wechsel: Von None zu einem Typ ODER von einem Typ zu einem anderen
|
|
is_section_type_change_step2 = (
|
|
current_chunk_text and # Es gibt bereits Content
|
|
(
|
|
# Wechsel von None zu einem Typ
|
|
(current_section_type_meta is None and item_section_type is not None) or
|
|
# Wechsel von einem Typ zu None
|
|
(current_section_type_meta is not None and item_section_type is None) or
|
|
# Wechsel zwischen verschiedenen Typen
|
|
(current_section_type_meta is not None and item_section_type is not None
|
|
and current_section_type_meta != item_section_type)
|
|
)
|
|
)
|
|
|
|
if is_section_type_change_step2:
|
|
# WP-26 v1.1: Section-Type-Wechsel erzwingt Split
|
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"],
|
|
current_meta["section_type"], current_meta["block_id"])
|
|
current_chunk_text = ""
|
|
# Reset Meta für nächsten Chunk
|
|
current_meta["title"] = item["meta"].section_title
|
|
current_meta["path"] = item["meta"].section_path
|
|
current_meta["section_type"] = item_section_type
|
|
current_meta["block_id"] = item.get("block_id")
|
|
|
|
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_meta["section_type"], current_meta["block_id"])
|
|
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"],
|
|
current_meta["section_type"], current_meta["block_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
|
|
# WP-26 v1.0: section_type und block_id weitergeben
|
|
queue.insert(0, {"text": remainder, "meta": item["meta"], "is_split": True,
|
|
"section_type": item.get("section_type"), "block_id": item.get("block_id")})
|
|
|
|
if current_chunk_text:
|
|
_emit(current_chunk_text, current_meta["title"], current_meta["path"],
|
|
current_meta["section_type"], current_meta["block_id"])
|
|
|
|
return chunks
|
|
|
|
def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, context_prefix: str = "") -> List[Chunk]:
|
|
"""
|
|
Standard-Sliding-Window für flache Texte ohne Sektionsfokus.
|
|
WP-26 v1.0: Erweitert um section_type und block_id Weitergabe.
|
|
WP-26 v1.3: Parser propagiert section_type rückwirkend - vereinfachte Logik.
|
|
"""
|
|
target = config.get("target", 400); max_tokens = config.get("max", 600)
|
|
chunks: List[Chunk] = []; buf: List[RawBlock] = []
|
|
current_section_type = None # Tracking des aktuellen section_type
|
|
|
|
def _flush_buffer():
|
|
"""Hilfsfunktion zum Flushen des Buffers."""
|
|
nonlocal buf, current_section_type
|
|
if not buf:
|
|
return
|
|
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
|
|
win = _create_win(context_prefix, buf[0].section_title, txt)
|
|
# WP-26 v1.3: section_type wird bereits vom Parser rückwirkend propagiert
|
|
effective_section_type = next((b.section_type for b in buf if b.section_type), None)
|
|
effective_block_id = next((b.block_id for b in buf if b.block_id), None)
|
|
chunks.append(Chunk(
|
|
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
|
text=txt, window=win, token_count=sum(estimate_tokens(x.text) for x in buf),
|
|
section_title=buf[0].section_title, section_path=buf[0].section_path,
|
|
neighbors_prev=None, neighbors_next=None,
|
|
section_type=effective_section_type, block_id=effective_block_id
|
|
))
|
|
buf = []
|
|
current_section_type = effective_section_type
|
|
|
|
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
|
|
block_section_type = b.section_type
|
|
|
|
# WP-26 v1.3: Prüfe auf Section-Type-Wechsel
|
|
# Da der Parser section_type rückwirkend setzt, haben alle Blöcke einer
|
|
# Heading-Sektion denselben section_type. Ein Wechsel bedeutet neue Sektion.
|
|
is_section_type_change = (
|
|
buf and # Es gibt bereits Blöcke im Buffer
|
|
current_section_type != block_section_type # Typ hat sich geändert
|
|
)
|
|
|
|
# Flush wenn: Token-Limit überschritten ODER Section-Type-Wechsel
|
|
if (curr_tokens + b_tokens > max_tokens and buf) or is_section_type_change:
|
|
_flush_buffer()
|
|
|
|
buf.append(b)
|
|
# Update section_type
|
|
if block_section_type:
|
|
current_section_type = block_section_type
|
|
|
|
# Letzten Buffer flushen
|
|
_flush_buffer()
|
|
|
|
return chunks |