mindnet/app/core/chunker.py

334 lines
12 KiB
Python
Raw Normal View History

2025-09-03 07:15:00 +02:00
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Dict, Optional, Tuple, Any, Set
2025-09-03 07:15:00 +02:00
import re
import math
2025-12-11 22:39:35 +01:00
import yaml
from pathlib import Path
2025-09-03 07:15:00 +02:00
from markdown_it import MarkdownIt
from markdown_it.token import Token
2025-12-12 09:02:32 +01:00
import asyncio
2025-12-12 10:25:01 +01:00
import logging
2025-12-11 22:39:35 +01:00
2025-12-12 11:40:38 +01:00
# Services
from app.services.semantic_analyzer import get_semantic_analyzer
2025-12-12 11:45:43 +01:00
# Core Imports
2025-12-12 10:25:01 +01:00
try:
from app.core.derive_edges import build_edges_for_note
except ImportError:
2025-12-12 11:45:43 +01:00
# Mock für Tests
def build_edges_for_note(md_text, note_id, note_type, chunks=[], references=[]): return []
2025-12-12 08:57:25 +01:00
2025-12-12 10:25:01 +01:00
logger = logging.getLogger(__name__)
# ==========================================
2025-12-12 11:40:38 +01:00
# 1. HELPER & CONFIG
2025-12-12 10:25:01 +01:00
# ==========================================
BASE_DIR = Path(__file__).resolve().parent.parent.parent
CONFIG_PATH = BASE_DIR / "config" / "types.yaml"
DEFAULT_PROFILE = {"strategy": "sliding_window", "target": 400, "max": 600, "overlap": (50, 80)}
_CONFIG_CACHE = None
2025-12-12 11:40:38 +01:00
2025-12-12 10:25:01 +01:00
def _load_yaml_config() -> Dict[str, Any]:
global _CONFIG_CACHE
2025-12-12 10:27:57 +01:00
if _CONFIG_CACHE is not None: return _CONFIG_CACHE
if not CONFIG_PATH.exists(): return {}
2025-12-12 10:25:01 +01:00
try:
2025-12-12 11:40:38 +01:00
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
_CONFIG_CACHE = data
return data
except Exception: return {}
2025-12-12 10:25:01 +01:00
def get_chunk_config(note_type: str) -> Dict[str, Any]:
2025-12-12 11:40:38 +01:00
full_config = _load_yaml_config()
profiles = full_config.get("chunking_profiles", {})
type_def = full_config.get("types", {}).get(note_type.lower(), {})
profile_name = type_def.get("chunking_profile")
if not profile_name:
profile_name = full_config.get("defaults", {}).get("chunking_profile", "sliding_standard")
2025-12-12 10:25:01 +01:00
config = profiles.get(profile_name, DEFAULT_PROFILE).copy()
2025-12-12 11:40:38 +01:00
if "overlap" in config and isinstance(config["overlap"], list):
config["overlap"] = tuple(config["overlap"])
2025-12-12 10:25:01 +01:00
return config
2025-12-12 11:40:38 +01:00
def extract_frontmatter_from_text(md_text: str) -> Tuple[Dict[str, Any], str]:
fm_match = re.match(r'^\s*---\s*\n(.*?)\n---', md_text, re.DOTALL)
if not fm_match: return {}, md_text
try:
frontmatter = yaml.safe_load(fm_match.group(1))
if not isinstance(frontmatter, dict): frontmatter = {}
except yaml.YAMLError:
frontmatter = {}
text_without_fm = re.sub(r'^\s*---\s*\n(.*?)\n---', '', md_text, flags=re.DOTALL)
return frontmatter, text_without_fm.strip()
2025-12-12 10:25:01 +01:00
# ==========================================
2025-12-12 11:40:38 +01:00
# 2. DATA CLASSES
2025-12-12 10:25:01 +01:00
# ==========================================
2025-12-12 11:45:43 +01:00
_SENT_SPLIT = re.compile(r'(?<=[.!?])\s+(?=[A-ZÄÖÜ0-9„(])')
_WS = re.compile(r'\s+')
2025-12-12 11:40:38 +01:00
2025-12-12 10:25:01 +01:00
def estimate_tokens(text: str) -> int:
2025-12-12 11:40:38 +01:00
return max(1, math.ceil(len(text.strip()) / 4))
2025-12-12 10:25:01 +01:00
def split_sentences(text: str) -> list[str]:
text = _WS.sub(' ', text.strip())
2025-12-12 10:30:38 +01:00
if not text: return []
2025-12-12 10:25:01 +01:00
parts = _SENT_SPLIT.split(text)
return [p.strip() for p in parts if p.strip()]
@dataclass
class RawBlock:
kind: str; text: str; level: Optional[int]; section_path: str; section_title: Optional[str]
@dataclass
class Chunk:
2025-12-12 11:40:38 +01:00
id: str; note_id: str; index: int; text: str; window: str; token_count: int
section_title: Optional[str]; section_path: str
neighbors_prev: Optional[str]; neighbors_next: Optional[str]
suggested_edges: Optional[List[str]] = None
# ==========================================
# 3. PARSING & STRATEGIES (SYNCHRON)
# ==========================================
2025-12-12 10:25:01 +01:00
def parse_blocks(md_text: str) -> Tuple[List[RawBlock], str]:
2025-12-12 11:45:43 +01:00
"""
Zerlegt Text in logische Blöcke (Absätze, Header).
Verbesserte Version: Splittet auch reine Absätze.
"""
blocks = []
h1_title = "Dokument"
section_path = "/"
current_h2 = None
2025-12-12 10:25:01 +01:00
fm, text_without_fm = extract_frontmatter_from_text(md_text)
2025-12-12 11:40:38 +01:00
2025-12-12 11:45:43 +01:00
# H1 suchen
2025-12-12 10:25:01 +01:00
h1_match = re.search(r'^#\s+(.*)', text_without_fm, re.MULTILINE)
2025-12-12 11:45:43 +01:00
if h1_match:
h1_title = h1_match.group(1).strip()
# Rudimentäres Parsing (Markdown-It ist komplex einzubinden ohne vollen Visitor)
# Wir splitten hier einfach an Doppel-Newlines für Paragraphen, wenn keine Header da sind.
2025-12-12 11:40:38 +01:00
2025-12-12 11:45:43 +01:00
# Zuerst Header-Struktur bewahren
lines = text_without_fm.split('\n')
buffer = []
for line in lines:
stripped = line.strip()
if stripped.startswith('# '): # H1 ignorieren wir im Body meist
continue
elif stripped.startswith('## '):
# Flush buffer
if buffer:
content = "\n".join(buffer).strip()
if content:
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
buffer = []
current_h2 = stripped[3:].strip()
section_path = f"/{current_h2}"
blocks.append(RawBlock("heading", stripped, 2, section_path, current_h2))
elif not stripped:
# Leere Zeile -> Absatzende
if buffer:
content = "\n".join(buffer).strip()
if content:
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
buffer = []
else:
buffer.append(line)
if buffer:
content = "\n".join(buffer).strip()
if content:
blocks.append(RawBlock("paragraph", content, None, section_path, current_h2))
2025-12-12 10:25:01 +01:00
return blocks, h1_title
def _strategy_sliding_window(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "", context_prefix: str = "") -> List[Chunk]:
2025-12-12 11:45:43 +01:00
target = config.get("target", 400)
max_tokens = config.get("max", 600)
2025-12-12 11:40:38 +01:00
overlap_val = config.get("overlap", (50, 80))
overlap = sum(overlap_val) // 2 if isinstance(overlap_val, tuple) else overlap_val
2025-12-12 11:45:43 +01:00
chunks = []
buf = [] # Buffer für Blöcke
2025-12-12 11:40:38 +01:00
2025-12-12 11:45:43 +01:00
def _create_chunk(txt, win, sec, path):
idx = len(chunks)
2025-12-12 11:40:38 +01:00
chunks.append(Chunk(
2025-12-12 11:45:43 +01:00
id=f"{note_id}#c{idx:02d}", note_id=note_id, index=idx,
2025-12-12 11:40:38 +01:00
text=txt, window=win, token_count=estimate_tokens(txt),
section_title=sec, section_path=path, neighbors_prev=None, neighbors_next=None,
suggested_edges=[]
))
2025-12-12 10:25:01 +01:00
def flush_buffer():
nonlocal buf
if not buf: return
2025-12-12 11:45:43 +01:00
# Kombiniere Blöcke im Buffer
2025-12-12 10:25:01 +01:00
text_body = "\n\n".join([b.text for b in buf])
2025-12-12 11:45:43 +01:00
sec_title = buf[-1].section_title if buf else None
sec_path = buf[-1].section_path if buf else "/"
2025-12-12 11:40:38 +01:00
2025-12-12 11:45:43 +01:00
# Check Größe
2025-12-12 11:40:38 +01:00
if estimate_tokens(text_body) <= max_tokens:
2025-12-12 11:45:43 +01:00
win_body = f"{context_prefix}\n{text_body}".strip() if context_prefix else text_body
_create_chunk(text_body, win_body, sec_title, sec_path)
2025-12-12 10:25:01 +01:00
else:
2025-12-12 11:45:43 +01:00
# Text ist zu groß -> Splitte nach Sätzen
sentences = split_sentences(text_body)
current_chunk_sents = []
current_len = 0
for sent in sentences:
sent_len = estimate_tokens(sent)
if current_len + sent_len > target and current_chunk_sents:
# Chunk abschließen
c_txt = " ".join(current_chunk_sents)
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
_create_chunk(c_txt, c_win, sec_title, sec_path)
# Overlap für nächsten Chunk
# Wir nehmen die letzten Sätze, die in den Overlap passen
overlap_sents = []
ov_len = 0
for s in reversed(current_chunk_sents):
if ov_len + estimate_tokens(s) < overlap:
overlap_sents.insert(0, s)
ov_len += estimate_tokens(s)
else:
break
current_chunk_sents = list(overlap_sents)
current_chunk_sents.append(sent)
current_len = ov_len + sent_len
else:
current_chunk_sents.append(sent)
current_len += sent_len
# Rest verarbeiten
if current_chunk_sents:
c_txt = " ".join(current_chunk_sents)
c_win = f"{context_prefix}\n{c_txt}".strip() if context_prefix else c_txt
_create_chunk(c_txt, c_win, sec_title, sec_path)
2025-12-12 10:25:01 +01:00
buf = []
for b in blocks:
2025-12-12 11:45:43 +01:00
if b.kind == "heading": continue # Header nicht direkt in Text mischen, dienen nur Struktur
# Wenn Buffer + neuer Block zu groß -> Flush
current_buf_text = "\n\n".join([x.text for x in buf])
if estimate_tokens(current_buf_text) + estimate_tokens(b.text) >= target:
2025-12-12 10:25:01 +01:00
flush_buffer()
2025-12-12 11:45:43 +01:00
2025-12-12 10:25:01 +01:00
buf.append(b)
2025-12-12 11:45:43 +01:00
# Wenn der Block selbst riesig ist (größer als Target), sofort flushen und splitten
if estimate_tokens(b.text) >= target:
flush_buffer()
2025-12-12 10:25:01 +01:00
flush_buffer()
return chunks
def _strategy_by_heading(blocks: List[RawBlock], config: Dict[str, Any], note_id: str, doc_title: str = "") -> List[Chunk]:
2025-12-12 11:40:38 +01:00
return _strategy_sliding_window(blocks, config, note_id, doc_title, context_prefix=f"# {doc_title}")
2025-12-12 10:25:01 +01:00
# ==========================================
2025-12-12 11:40:38 +01:00
# 4. ORCHESTRATION (ASYNC) - WP-15 CORE
2025-12-12 10:25:01 +01:00
# ==========================================
2025-12-12 11:40:38 +01:00
async def assemble_chunks(note_id: str, md_text: str, note_type: str, config: Optional[Dict] = None) -> List[Chunk]:
if config is None:
config = get_chunk_config(note_type)
fm, body_text = extract_frontmatter_from_text(md_text)
note_status = fm.get("status", "").lower()
2025-12-12 11:40:38 +01:00
primary_strategy = config.get("strategy", "sliding_window")
enable_smart_edges = config.get("enable_smart_edge_allocation", False)
2025-12-12 10:25:01 +01:00
2025-12-12 11:40:38 +01:00
if enable_smart_edges and note_status in ["draft", "initial_gen"]:
logger.info(f"Chunker: Skipping Smart Edges for draft '{note_id}'.")
enable_smart_edges = False
2025-12-12 10:25:01 +01:00
2025-12-12 11:40:38 +01:00
blocks, doc_title = parse_blocks(md_text)
2025-12-12 10:25:01 +01:00
if primary_strategy == "by_heading":
chunks = await asyncio.to_thread(_strategy_by_heading, blocks, config, note_id, doc_title)
2025-12-12 11:40:38 +01:00
else:
chunks = await asyncio.to_thread(_strategy_sliding_window, blocks, config, note_id, doc_title)
2025-12-12 11:40:38 +01:00
if not chunks:
return []
2025-12-11 22:39:35 +01:00
2025-12-12 11:40:38 +01:00
if enable_smart_edges:
chunks = await _run_smart_edge_allocation(chunks, md_text, note_id, note_type)
2025-12-11 23:21:24 +01:00
2025-12-12 11:40:38 +01:00
for i, ch in enumerate(chunks):
ch.neighbors_prev = chunks[i-1].id if i > 0 else None
ch.neighbors_next = chunks[i+1].id if i < len(chunks)-1 else None
2025-12-12 10:25:01 +01:00
2025-12-12 11:40:38 +01:00
return chunks
async def _run_smart_edge_allocation(chunks: List[Chunk], full_text: str, note_id: str, note_type: str) -> List[Chunk]:
analyzer = get_semantic_analyzer()
2025-12-12 10:25:01 +01:00
2025-12-12 11:45:43 +01:00
# FIX: Positional Argument für text übergeben, um TypeError zu vermeiden
2025-12-12 11:40:38 +01:00
raw_edges = build_edges_for_note(
2025-12-12 11:45:43 +01:00
full_text,
2025-12-12 11:40:38 +01:00
note_id=note_id,
note_type=note_type,
chunks=[],
2025-12-12 11:45:43 +01:00
references=[] # Falls die Signatur references erwartet
2025-12-12 11:40:38 +01:00
)
2025-12-12 10:25:01 +01:00
2025-12-12 11:40:38 +01:00
all_candidates = set()
2025-12-12 11:45:43 +01:00
# Robustheit: raw_edges könnte None sein, falls der Mock schlecht ist
if raw_edges:
for e in raw_edges:
if e.get("target_id") and e.get("kind") not in ["next", "prev", "belongs_to"]:
all_candidates.add(f"{e['kind']}:{e['target_id']}")
2025-12-12 08:47:12 +01:00
2025-12-12 11:40:38 +01:00
candidate_list = list(all_candidates)
2025-12-12 08:47:12 +01:00
2025-12-12 11:40:38 +01:00
if not candidate_list:
2025-12-12 11:45:43 +01:00
return chunks
2025-12-12 11:40:38 +01:00
tasks = []
for chunk in chunks:
tasks.append(analyzer.assign_edges_to_chunk(chunk.text, candidate_list, note_type))
2025-12-11 22:39:35 +01:00
2025-12-12 11:40:38 +01:00
results_per_chunk = await asyncio.gather(*tasks)
2025-12-12 10:25:01 +01:00
2025-12-12 11:40:38 +01:00
assigned_edges_global = set()
2025-12-11 23:21:24 +01:00
2025-12-12 11:40:38 +01:00
for i, confirmed_edges in enumerate(results_per_chunk):
chunk = chunks[i]
chunk.suggested_edges = confirmed_edges
assigned_edges_global.update(confirmed_edges)
2025-12-12 10:25:01 +01:00
2025-12-12 11:40:38 +01:00
if confirmed_edges:
injection_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in confirmed_edges if ':' in e])
chunk.text += injection_str
chunk.window += injection_str
unassigned = set(candidate_list) - assigned_edges_global
if unassigned:
fallback_str = "\n" + " ".join([f"[[rel:{e.split(':')[0]}|{e.split(':')[1]}]]" for e in unassigned if ':' in e])
for chunk in chunks:
chunk.text += fallback_str
chunk.window += fallback_str
if chunk.suggested_edges is None: chunk.suggested_edges = []
chunk.suggested_edges.extend(list(unassigned))
2025-12-12 10:25:01 +01:00
return chunks