mindnet/app/core/chunk_payload.py

165 lines
5.8 KiB
Python
Raw Normal View History

2025-11-11 16:58:22 +01:00
"""
2025-12-15 15:40:39 +01:00
FILE: app/core/chunk_payload.py
2025-12-16 15:52:50 +01:00
DESCRIPTION: Baut das JSON-Objekt für 'mindnet_chunks'.
FEATURES:
- Inkludiert Nachbarschafts-IDs (prev/next) und Titel.
2025-12-16 15:52:50 +01:00
- FIX 1: Korrektes Auslesen von 'chunking_profile' (Frontmatter > Type > Default).
- FIX 2: Korrektes Vererben von 'retriever_weight' (Frontmatter > Type > Default).
VERSION: 2.2.0
2025-12-15 15:40:39 +01:00
STATUS: Active
DEPENDENCIES: yaml, os
EXTERNAL_CONFIG: config/types.yaml
2025-11-11 16:58:22 +01:00
"""
2025-11-09 10:11:34 +01:00
from __future__ import annotations
2025-11-11 16:58:22 +01:00
from typing import Any, Dict, List, Optional
2025-11-16 18:51:06 +01:00
import os, yaml
2025-11-11 16:58:22 +01:00
2025-11-16 18:51:06 +01:00
def _env(n: str, d: Optional[str]=None) -> str:
v = os.getenv(n)
return v if v is not None else (d or "")
2025-11-11 17:04:53 +01:00
2025-11-16 21:20:10 +01:00
def _load_types() -> dict:
2025-11-16 18:51:06 +01:00
p = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
2025-11-09 10:11:34 +01:00
try:
2025-11-16 18:51:06 +01:00
with open(p, "r", encoding="utf-8") as f:
return yaml.safe_load(f) or {}
2025-11-09 10:11:34 +01:00
except Exception:
2025-11-16 18:51:06 +01:00
return {}
2025-11-16 21:20:10 +01:00
def _get_types_map(reg: dict) -> dict:
if isinstance(reg, dict) and isinstance(reg.get("types"), dict):
return reg["types"]
return reg if isinstance(reg, dict) else {}
2025-11-16 18:51:06 +01:00
2025-11-16 21:20:10 +01:00
def _get_defaults(reg: dict) -> dict:
if isinstance(reg, dict) and isinstance(reg.get("defaults"), dict):
return reg["defaults"]
if isinstance(reg, dict) and isinstance(reg.get("global"), dict):
return reg["global"]
return {}
def _as_float(x: Any):
try: return float(x)
except Exception: return None
def _resolve_chunk_profile_from_config(note_type: str, reg: dict) -> Optional[str]:
# 1. Type Level
2025-11-16 21:20:10 +01:00
types = _get_types_map(reg)
if isinstance(types, dict):
t = types.get(note_type, {})
if isinstance(t, dict):
cp = t.get("chunking_profile") or t.get("chunk_profile")
2025-12-16 15:52:50 +01:00
if isinstance(cp, str) and cp: return cp
# 2. Defaults Level
2025-11-16 21:20:10 +01:00
defs = _get_defaults(reg)
if isinstance(defs, dict):
cp = defs.get("chunking_profile") or defs.get("chunk_profile")
2025-12-16 15:52:50 +01:00
if isinstance(cp, str) and cp: return cp
return None
2025-11-16 21:20:10 +01:00
2025-12-16 15:52:50 +01:00
def _resolve_retriever_weight_from_config(note_type: str, reg: dict) -> float:
"""
Liest Weight nur aus Config (Type > Default).
Wird aufgerufen, wenn im Frontmatter nichts steht.
"""
# 1. Type Level
2025-11-16 21:20:10 +01:00
types = _get_types_map(reg)
if isinstance(types, dict):
t = types.get(note_type, {})
if isinstance(t, dict) and (t.get("retriever_weight") is not None):
v = _as_float(t.get("retriever_weight"))
if v is not None: return float(v)
2025-12-16 15:52:50 +01:00
# 2. Defaults Level
2025-11-16 21:20:10 +01:00
defs = _get_defaults(reg)
if isinstance(defs, dict) and (defs.get("retriever_weight") is not None):
v = _as_float(defs.get("retriever_weight"))
if v is not None: return float(v)
2025-12-16 15:52:50 +01:00
2025-11-16 18:51:06 +01:00
return 1.0
2025-11-16 18:56:33 +01:00
def _as_list(x):
if x is None: return []
if isinstance(x, list): return x
2025-11-16 18:56:33 +01:00
return [x]
2025-11-16 18:51:06 +01:00
def make_chunk_payloads(note: Dict[str, Any],
note_path: str,
chunks_from_chunker: List[Any],
*,
note_text: str = "",
types_cfg: Optional[dict] = None,
file_path: Optional[str] = None) -> List[Dict[str, Any]]:
"""
Erstellt die Payloads für die Chunks.
"""
2025-11-16 18:56:33 +01:00
fm = (note or {}).get("frontmatter", {}) or {}
2025-11-16 18:51:06 +01:00
note_type = fm.get("type") or note.get("type") or "concept"
2025-12-11 07:34:31 +01:00
# Title Extraction
2025-12-11 07:34:31 +01:00
title = fm.get("title") or note.get("title") or fm.get("id") or "Untitled"
2025-11-16 21:20:10 +01:00
reg = types_cfg if isinstance(types_cfg, dict) else _load_types()
2025-11-16 18:51:06 +01:00
2025-12-16 15:52:50 +01:00
# --- Profil-Ermittlung (Fix aus v2.1.0) ---
cp = fm.get("chunking_profile") or fm.get("chunk_profile")
if not cp:
cp = _resolve_chunk_profile_from_config(note_type, reg)
if not cp:
2025-12-16 15:52:50 +01:00
cp = "sliding_standard"
2025-12-16 15:52:50 +01:00
# --- FIX 2: Retriever Weight Ermittlung ---
# 1. Frontmatter Override prüfen
rw = fm.get("retriever_weight")
# 2. Falls nicht im Frontmatter, aus Config laden
if rw is None:
rw = _resolve_retriever_weight_from_config(note_type, reg)
# 3. Sicherstellen, dass es ein Float ist
try:
rw = float(rw)
except Exception:
rw = 1.0
2025-11-16 18:51:06 +01:00
tags = fm.get("tags") or []
if isinstance(tags, str):
tags = [tags]
out: List[Dict[str, Any]] = []
for idx, ch in enumerate(chunks_from_chunker):
2025-12-16 15:52:50 +01:00
# Attribute extrahieren
2025-11-16 18:51:06 +01:00
cid = getattr(ch, "id", None) or (ch.get("id") if isinstance(ch, dict) else None)
nid = getattr(ch, "note_id", None) or (ch.get("note_id") if isinstance(ch, dict) else fm.get("id"))
index = getattr(ch, "index", None) or (ch.get("index") if isinstance(ch, dict) else idx)
text = getattr(ch, "text", None) or (ch.get("text") if isinstance(ch, dict) else "")
window = getattr(ch, "window", None) or (ch.get("window") if isinstance(ch, dict) else text)
prev_id = getattr(ch, "neighbors_prev", None) or (ch.get("neighbors_prev") if isinstance(ch, dict) else None)
next_id = getattr(ch, "neighbors_next", None) or (ch.get("neighbors_next") if isinstance(ch, dict) else None)
pl: Dict[str, Any] = {
"note_id": nid,
"chunk_id": cid,
"title": title,
2025-11-16 18:51:06 +01:00
"index": int(index),
"ord": int(index) + 1,
2025-11-09 10:11:34 +01:00
"type": note_type,
2025-11-16 18:51:06 +01:00
"tags": tags,
2025-11-11 17:04:53 +01:00
"text": text,
2025-11-16 18:51:06 +01:00
"window": window,
2025-11-16 18:56:33 +01:00
"neighbors_prev": _as_list(prev_id),
"neighbors_next": _as_list(next_id),
2025-11-16 18:51:06 +01:00
"section": getattr(ch, "section", None) or (ch.get("section") if isinstance(ch, dict) else ""),
"path": note_path,
"source_path": file_path or note_path,
2025-12-16 15:52:50 +01:00
"retriever_weight": float(rw), # Jetzt korrekt vererbt
"chunk_profile": cp,
2025-11-09 10:11:34 +01:00
}
# Cleanup
2025-11-16 18:51:06 +01:00
for alias in ("chunk_num", "Chunk_Number"):
2025-11-16 18:56:33 +01:00
pl.pop(alias, None)
2025-11-16 18:51:06 +01:00
out.append(pl)
2025-12-11 07:34:31 +01:00
return out