Aktualisierung des Chunking-Parsers zur Verbesserung der Blockverarbeitung und Beschreibung. Anpassungen an der atomaren Sektions-Chunking-Strategie mit optimierter Token-Schätzung und neuen Hilfsfunktionen zur besseren Handhabung von großen Sektionen.
This commit is contained in:
parent
b1a897e51c
commit
96b4f65cd1
|
|
@ -1,7 +1,7 @@
|
||||||
"""
|
"""
|
||||||
FILE: app/core/chunking/chunking_parser.py
|
FILE: app/core/chunking/chunking_parser.py
|
||||||
DESCRIPTION: Zerlegt Markdown in logische Blöcke. Hält H1-Überschriften im Stream
|
DESCRIPTION: Zerlegt Markdown in logische Einheiten (RawBlocks).
|
||||||
und optimiert die Block-Trennung für atomares Sektions-Chunking.
|
Hält H1-Überschriften im Inhalts-Stream.
|
||||||
"""
|
"""
|
||||||
import re
|
import re
|
||||||
from typing import List, Tuple, Set
|
from typing import List, Tuple, Set
|
||||||
|
|
@ -15,7 +15,6 @@ def split_sentences(text: str) -> list[str]:
|
||||||
"""Teilt Text in Sätze auf unter Berücksichtigung deutscher Interpunktion."""
|
"""Teilt Text in Sätze auf unter Berücksichtigung deutscher Interpunktion."""
|
||||||
text = _WS.sub(' ', text.strip())
|
text = _WS.sub(' ', text.strip())
|
||||||
if not text: return []
|
if not text: return []
|
||||||
# Splittet bei Satzzeichen, gefolgt von Leerzeichen und Großbuchstaben
|
|
||||||
return [p.strip() for p in _SENT_SPLIT.split(text) if p.strip()]
|
return [p.strip() for p in _SENT_SPLIT.split(text) if p.strip()]
|
||||||
|
|
||||||
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
|
|
@ -28,7 +27,7 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
# Frontmatter entfernen
|
# Frontmatter entfernen
|
||||||
fm, text_without_fm = extract_frontmatter_from_text(md_text)
|
fm, text_without_fm = extract_frontmatter_from_text(md_text)
|
||||||
|
|
||||||
# H1 für Note-Metadaten extrahieren
|
# H1 für Note-Titel extrahieren
|
||||||
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
|
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
|
||||||
if h1_match:
|
if h1_match:
|
||||||
h1_title = h1_match.group(1).strip()
|
h1_title = h1_match.group(1).strip()
|
||||||
|
|
@ -42,7 +41,7 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
# Heading-Erkennung (H1 bis H6)
|
# Heading-Erkennung (H1 bis H6)
|
||||||
heading_match = re.match(r'^(#{1,6})\s+(.*)', stripped)
|
heading_match = re.match(r'^(#{1,6})\s+(.*)', stripped)
|
||||||
if heading_match:
|
if heading_match:
|
||||||
# Vorherigen Block abschließen
|
# Vorherigen Text-Block abschließen
|
||||||
if buffer:
|
if buffer:
|
||||||
content = "\n".join(buffer).strip()
|
content = "\n".join(buffer).strip()
|
||||||
if content:
|
if content:
|
||||||
|
|
@ -52,7 +51,7 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
level = len(heading_match.group(1))
|
level = len(heading_match.group(1))
|
||||||
title = heading_match.group(2).strip()
|
title = heading_match.group(2).strip()
|
||||||
|
|
||||||
# Update der Pfad-Metadaten für die folgenden Blöcke
|
# Pfad- und Titel-Update für die Metadaten der folgenden Blöcke
|
||||||
if level == 1:
|
if level == 1:
|
||||||
current_section_title = title
|
current_section_title = title
|
||||||
section_path = "/"
|
section_path = "/"
|
||||||
|
|
@ -60,11 +59,11 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
current_section_title = title
|
current_section_title = title
|
||||||
section_path = f"/{current_section_title}"
|
section_path = f"/{current_section_title}"
|
||||||
|
|
||||||
# Die Überschrift als regulären Block hinzufügen (Fix: H1 bleibt im Text)
|
# Die Überschrift selbst als Block hinzufügen
|
||||||
blocks.append(RawBlock("heading", stripped, level, section_path, current_section_title))
|
blocks.append(RawBlock("heading", stripped, level, section_path, current_section_title))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Trenner (---) oder Leerzeilen beenden Blöcke, außer in Callouts
|
# Trenner oder Leerzeilen beenden Blöcke, außer innerhalb von Callouts
|
||||||
if (not stripped or stripped == "---") and not line.startswith('>'):
|
if (not stripped or stripped == "---") and not line.startswith('>'):
|
||||||
if buffer:
|
if buffer:
|
||||||
content = "\n".join(buffer).strip()
|
content = "\n".join(buffer).strip()
|
||||||
|
|
@ -76,7 +75,6 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
else:
|
else:
|
||||||
buffer.append(line)
|
buffer.append(line)
|
||||||
|
|
||||||
# Letzten Puffer leeren
|
|
||||||
if buffer:
|
if buffer:
|
||||||
content = "\n".join(buffer).strip()
|
content = "\n".join(buffer).strip()
|
||||||
if content:
|
if content:
|
||||||
|
|
@ -87,14 +85,12 @@ def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
|
||||||
def parse_edges_robust(text: str) -> Set[str]:
|
def parse_edges_robust(text: str) -> Set[str]:
|
||||||
"""Extrahiert Kanten-Kandidaten aus Wikilinks und Callouts."""
|
"""Extrahiert Kanten-Kandidaten aus Wikilinks und Callouts."""
|
||||||
found_edges = set()
|
found_edges = set()
|
||||||
# 1. Wikilinks [[rel:kind|target]]
|
|
||||||
inlines = re.findall(r'\[\[rel:([^\|\]]+)\|?([^\]]*)\]\]', text)
|
inlines = re.findall(r'\[\[rel:([^\|\]]+)\|?([^\]]*)\]\]', text)
|
||||||
for kind, target in inlines:
|
for kind, target in inlines:
|
||||||
k = kind.strip().lower()
|
k = kind.strip().lower()
|
||||||
t = target.strip()
|
t = target.strip()
|
||||||
if k and t: found_edges.add(f"{k}:{t}")
|
if k and t: found_edges.add(f"{k}:{t}")
|
||||||
|
|
||||||
# 2. Callout Edges > [!edge] kind
|
|
||||||
lines = text.split('\n')
|
lines = text.split('\n')
|
||||||
current_edge_type = None
|
current_edge_type = None
|
||||||
for line in lines:
|
for line in lines:
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,15 @@
|
||||||
"""
|
"""
|
||||||
FILE: app/core/chunking/chunking_strategies.py
|
FILE: app/core/chunking/chunking_strategies.py
|
||||||
DESCRIPTION: Strategien für atomares Sektions-Chunking v3.4.1.
|
DESCRIPTION: Universelle Strategie für atomares Sektions-Chunking v3.5.0.
|
||||||
Garantiert Sektions-Integrität (Atomic Units) durch Look-Ahead.
|
Garantiert Sektions-Integrität durch präventives Chunk-Management.
|
||||||
"""
|
"""
|
||||||
import math
|
|
||||||
from typing import List, Dict, Any, Optional
|
from typing import List, Dict, Any, Optional
|
||||||
from .chunking_models import RawBlock, Chunk
|
from .chunking_models import RawBlock, Chunk
|
||||||
from .chunking_utils import estimate_tokens
|
from .chunking_utils import estimate_tokens
|
||||||
from .chunking_parser import split_sentences
|
from .chunking_parser import split_sentences
|
||||||
|
|
||||||
def _safe_estimate_tokens(text: str) -> int:
|
|
||||||
"""Konservative Schätzung für MD und deutsche Texte (len/2.8)."""
|
|
||||||
return max(1, math.ceil(len(text.strip()) / 2.8))
|
|
||||||
|
|
||||||
def _create_context_win(doc_title: str, sec_title: Optional[str], text: str) -> str:
|
def _create_context_win(doc_title: str, sec_title: Optional[str], text: str) -> str:
|
||||||
"""Baut den Breadcrumb-Kontext für das Embedding-Fenster (H1 > H2)."""
|
"""Baut den Breadcrumb-Kontext für das Embedding-Fenster."""
|
||||||
parts = []
|
parts = []
|
||||||
if doc_title: parts.append(doc_title)
|
if doc_title: parts.append(doc_title)
|
||||||
if sec_title and sec_title != doc_title: parts.append(sec_title)
|
if sec_title and sec_title != doc_title: parts.append(sec_title)
|
||||||
|
|
@ -23,10 +18,9 @@ def _create_context_win(doc_title: str, sec_title: Optional[str], text: str) ->
|
||||||
|
|
||||||
def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
|
||||||
"""
|
"""
|
||||||
Sektions-Chunking: Behandelt Abschnitte als unteilbare Einheiten.
|
Universelles Sektions-Chunking: Packt Sektionen in Chunks.
|
||||||
Schiebt ganze Abschnitte in den nächsten Chunk, falls das Limit erreicht ist.
|
Bei Überlauf wird die komplette Sektion in den nächsten Chunk geschoben.
|
||||||
"""
|
"""
|
||||||
strict = config.get("strict_heading_split", False)
|
|
||||||
target = config.get("target", 400)
|
target = config.get("target", 400)
|
||||||
max_tokens = config.get("max", 600)
|
max_tokens = config.get("max", 600)
|
||||||
split_level = config.get("split_level", 2)
|
split_level = config.get("split_level", 2)
|
||||||
|
|
@ -35,24 +29,23 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
|
||||||
|
|
||||||
chunks: List[Chunk] = []
|
chunks: List[Chunk] = []
|
||||||
|
|
||||||
def _emit_chunk(block_list: List[RawBlock]):
|
# --- HILFSFUNKTION: Erzeugt einen Chunk aus einer Blockliste ---
|
||||||
"""Erzeugt ein finales Chunk-Objekt aus einer Liste von Blöcken."""
|
def _create_chunk_from_blocks(block_list: List[RawBlock]):
|
||||||
if not block_list: return
|
if not block_list: return
|
||||||
txt = "\n\n".join([b.text for b in block_list])
|
txt = "\n\n".join([b.text for b in block_list])
|
||||||
idx = len(chunks)
|
idx = len(chunks)
|
||||||
# Metadaten vom ersten Block der Gruppe (Header)
|
|
||||||
title = block_list[0].section_title
|
title = block_list[0].section_title
|
||||||
path = block_list[0].section_path
|
path = block_list[0].section_path
|
||||||
win = _create_context_win(doc_title, title, txt)
|
win = _create_context_win(doc_title, title, txt)
|
||||||
chunks.append(Chunk(
|
chunks.append(Chunk(
|
||||||
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
|
||||||
text=txt, window=win, token_count=_safe_estimate_tokens(txt),
|
text=txt, window=win, token_count=estimate_tokens(txt),
|
||||||
section_title=title, section_path=path,
|
section_title=title, section_path=path,
|
||||||
neighbors_prev=None, neighbors_next=None
|
neighbors_prev=None, neighbors_next=None
|
||||||
))
|
))
|
||||||
|
|
||||||
def _emit_split_section(sec_blocks: List[RawBlock]):
|
# --- HILFSFUNKTION: Splittet eine einzelne Sektion, die > max ist ---
|
||||||
"""Splittet eine einzelne Sektion, die für sich allein zu groß ist."""
|
def _split_giant_section(sec_blocks: List[RawBlock]):
|
||||||
full_text = "\n\n".join([b.text for b in sec_blocks])
|
full_text = "\n\n".join([b.text for b in sec_blocks])
|
||||||
main_title = sec_blocks[0].section_title
|
main_title = sec_blocks[0].section_title
|
||||||
main_path = sec_blocks[0].section_path
|
main_path = sec_blocks[0].section_path
|
||||||
|
|
@ -62,15 +55,17 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
|
||||||
cur_sents = []; sub_len = 0
|
cur_sents = []; sub_len = 0
|
||||||
|
|
||||||
for s in sents:
|
for s in sents:
|
||||||
slen = _safe_estimate_tokens(s)
|
slen = estimate_tokens(s)
|
||||||
if sub_len + slen > target and cur_sents:
|
if sub_len + slen > target and cur_sents:
|
||||||
_emit_chunk([RawBlock("paragraph", " ".join(cur_sents), None, main_path, main_title)])
|
combined_text = " ".join(cur_sents)
|
||||||
# Header Injection für den Kontext im nächsten Teil-Chunk
|
_create_chunk_from_blocks([RawBlock("paragraph", combined_text, None, main_path, main_title)])
|
||||||
|
|
||||||
|
# Context Injection: Überschrift für den nächsten Teil-Chunk
|
||||||
ov_s = [header_text] if header_text else []
|
ov_s = [header_text] if header_text else []
|
||||||
ov_l = _safe_estimate_tokens(header_text) if header_text else 0
|
ov_l = estimate_tokens(header_text) if header_text else 0
|
||||||
for os in reversed(cur_sents):
|
for os in reversed(cur_sents):
|
||||||
if os == header_text: continue
|
if os == header_text: continue
|
||||||
t_len = _safe_estimate_tokens(os)
|
t_len = estimate_tokens(os)
|
||||||
if ov_l + t_len < overlap:
|
if ov_l + t_len < overlap:
|
||||||
ov_s.insert(len(ov_s)-1 if header_text else 0, os)
|
ov_s.insert(len(ov_s)-1 if header_text else 0, os)
|
||||||
ov_l += t_len
|
ov_l += t_len
|
||||||
|
|
@ -78,13 +73,15 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
|
||||||
cur_sents = list(ov_s); cur_sents.append(s); sub_len = ov_l + slen
|
cur_sents = list(ov_s); cur_sents.append(s); sub_len = ov_l + slen
|
||||||
else:
|
else:
|
||||||
cur_sents.append(s); sub_len += slen
|
cur_sents.append(s); sub_len += slen
|
||||||
if cur_sents:
|
|
||||||
_emit_chunk([RawBlock("paragraph", " ".join(cur_sents), None, main_path, main_title)])
|
|
||||||
|
|
||||||
# SCHRITT 1: Gruppierung in atomare Einheiten (Sektionen)
|
if cur_sents:
|
||||||
|
_create_chunk_from_blocks([RawBlock("paragraph", " ".join(cur_sents), None, main_path, main_title)])
|
||||||
|
|
||||||
|
# 1. SCHRITT: Gruppierung in atomare Sektions-Einheiten
|
||||||
sections: List[List[RawBlock]] = []
|
sections: List[List[RawBlock]] = []
|
||||||
curr_sec: List[RawBlock] = []
|
curr_sec: List[RawBlock] = []
|
||||||
for b in blocks:
|
for b in blocks:
|
||||||
|
# Eine neue Überschrift auf oder unter dem split_level startet eine neue Sektion
|
||||||
if b.kind == "heading" and b.level <= split_level:
|
if b.kind == "heading" and b.level <= split_level:
|
||||||
if curr_sec: sections.append(curr_sec)
|
if curr_sec: sections.append(curr_sec)
|
||||||
curr_sec = [b]
|
curr_sec = [b]
|
||||||
|
|
@ -92,54 +89,48 @@ def strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id:
|
||||||
curr_sec.append(b)
|
curr_sec.append(b)
|
||||||
if curr_sec: sections.append(curr_sec)
|
if curr_sec: sections.append(curr_sec)
|
||||||
|
|
||||||
# SCHRITT 2: Verarbeitung der Sektionen mit strengem Look-Ahead
|
# 2. SCHRITT: Sektionen in Chunks packen (Das universelle Pack-Verfahren)
|
||||||
current_chunk_buf = []
|
candidate_chunk: List[RawBlock] = []
|
||||||
current_tokens = 0
|
candidate_tokens = 0
|
||||||
|
|
||||||
for sec in sections:
|
for sec in sections:
|
||||||
sec_text = "\n\n".join([b.text for b in sec])
|
sec_text = "\n\n".join([b.text for b in sec])
|
||||||
sec_tokens = _safe_estimate_tokens(sec_text)
|
sec_tokens = estimate_tokens(sec_text)
|
||||||
|
|
||||||
if current_chunk_buf:
|
# Passt diese gesamte Sektion noch in den laufenden Chunk?
|
||||||
# PRÜFUNG: Würde die neue Sektion den aktuellen Chunk sprengen?
|
if candidate_tokens + sec_tokens <= max_tokens:
|
||||||
# ODER: Haben wir das Target bereits erreicht und fangen lieber neu an?
|
candidate_chunk.extend(sec)
|
||||||
if (current_tokens + sec_tokens > max_tokens) or (current_tokens >= target):
|
candidate_tokens = estimate_tokens("\n\n".join([b.text for b in candidate_chunk]))
|
||||||
_emit_chunk(current_chunk_buf)
|
|
||||||
current_chunk_buf = []
|
|
||||||
current_tokens = 0
|
|
||||||
# PRÜFUNG: Harter Split gefordert an Überschriften
|
|
||||||
elif strict and sec[0].kind == "heading" and sec[0].level == split_level:
|
|
||||||
_emit_chunk(current_chunk_buf)
|
|
||||||
current_chunk_buf = []
|
|
||||||
current_tokens = 0
|
|
||||||
|
|
||||||
# Wenn eine EINZELNE Sektion alleine schon das Limit sprengt
|
|
||||||
if sec_tokens > max_tokens:
|
|
||||||
if current_chunk_buf:
|
|
||||||
_emit_chunk(current_chunk_buf)
|
|
||||||
current_chunk_buf = []
|
|
||||||
current_tokens = 0
|
|
||||||
_emit_split_section(sec)
|
|
||||||
else:
|
else:
|
||||||
current_chunk_buf.extend(sec)
|
# Falls der aktuelle Chunk nicht leer ist: Raus damit, bevor die neue Sektion kommt
|
||||||
current_tokens += sec_tokens + 2 # +2 für Newline Join
|
if candidate_chunk:
|
||||||
|
_create_chunk_from_blocks(candidate_chunk)
|
||||||
|
candidate_chunk = []
|
||||||
|
candidate_tokens = 0
|
||||||
|
|
||||||
# Letzten Puffer schreiben
|
# Die neue Sektion ist nun allein. Ist sie selbst zu groß?
|
||||||
if current_chunk_buf:
|
if sec_tokens > max_tokens:
|
||||||
_emit_chunk(current_chunk_buf)
|
_split_giant_section(sec)
|
||||||
|
else:
|
||||||
|
candidate_chunk = list(sec)
|
||||||
|
candidate_tokens = sec_tokens
|
||||||
|
|
||||||
|
# Letzten Rest wegschreiben
|
||||||
|
if candidate_chunk:
|
||||||
|
_create_chunk_from_blocks(candidate_chunk)
|
||||||
|
|
||||||
return chunks
|
return chunks
|
||||||
|
|
||||||
def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, context_prefix: str = "") -> List[Chunk]:
|
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."""
|
"""Standard-Sliding-Window für flache Texte ohne Sektionsfokus."""
|
||||||
target = config.get("target", 400)
|
target = config.get("target", 400)
|
||||||
max_tokens = config.get("max", 600)
|
max_tokens = config.get("max", 600)
|
||||||
chunks: List[Chunk] = []
|
chunks: List[Chunk] = []
|
||||||
buf: List[RawBlock] = []
|
buf: List[RawBlock] = []
|
||||||
|
|
||||||
for b in blocks:
|
for b in blocks:
|
||||||
b_tokens = _safe_estimate_tokens(b.text)
|
b_tokens = estimate_tokens(b.text)
|
||||||
current_tokens = sum(_safe_estimate_tokens(x.text) for x in buf) if buf else 0
|
current_tokens = sum(estimate_tokens(x.text) for x in buf) if buf else 0
|
||||||
if current_tokens + b_tokens > max_tokens and buf:
|
if current_tokens + b_tokens > max_tokens and buf:
|
||||||
txt = "\n\n".join([x.text for x in buf])
|
txt = "\n\n".join([x.text for x in buf])
|
||||||
idx = len(chunks)
|
idx = len(chunks)
|
||||||
|
|
@ -150,5 +141,5 @@ def strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note
|
||||||
if buf:
|
if buf:
|
||||||
txt = "\n\n".join([x.text for x in buf]); idx = len(chunks)
|
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
|
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))
|
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
|
return chunks
|
||||||
Loading…
Reference in New Issue
Block a user