2025-11-11 16:58:22 +01:00
|
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
"""
|
|
|
|
|
|
app/core/chunk_payload.py — Mindnet V2 (compat)
|
|
|
|
|
|
|
2025-11-11 17:01:19 +01:00
|
|
|
|
Ziele:
|
2025-11-11 16:58:22 +01:00
|
|
|
|
- Bewahrt bestehendes Verhalten (index, chunk_profile, retriever_weight, etc.)
|
2025-11-11 17:01:19 +01:00
|
|
|
|
- Denormalisiert optional `tags` aus der Note‑FM auf Chunks
|
2025-11-11 16:58:22 +01:00
|
|
|
|
- Fügt Aliase für die Chunk‑Nummer hinzu: `ord` (v2‑Schema), `chunk_num`, `Chunk_Nummer`
|
2025-11-11 17:01:19 +01:00
|
|
|
|
- **Kompatibilität:** akzeptiert sowohl `path_arg` (positional) als auch `file_path` (keyword)
|
2025-11-11 16:58:22 +01:00
|
|
|
|
|
|
|
|
|
|
Hinweis:
|
2025-11-11 17:01:19 +01:00
|
|
|
|
- `edge_defaults` sind Note‑Regeln (Typ) und werden nicht pro Chunk gespiegelt.
|
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
|
|
|
|
|
|
|
|
|
|
import json
|
|
|
|
|
|
import os
|
|
|
|
|
|
import pathlib
|
|
|
|
|
|
import hashlib
|
|
|
|
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
|
|
|
|
|
|
|
|
from app.core.chunker import assemble_chunks
|
|
|
|
|
|
|
|
|
|
|
|
def _as_dict(obj):
|
|
|
|
|
|
if isinstance(obj, dict): return obj
|
|
|
|
|
|
try:
|
|
|
|
|
|
return dict(obj) # type: ignore
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return {"value": obj}
|
2025-11-09 10:11:34 +01:00
|
|
|
|
|
|
|
|
|
|
def _coalesce(*vals):
|
|
|
|
|
|
for v in vals:
|
|
|
|
|
|
if v is not None:
|
2025-11-09 09:51:05 +01:00
|
|
|
|
return v
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
2025-11-11 16:58:22 +01:00
|
|
|
|
def _env_float(name: str, default: float) -> float:
|
|
|
|
|
|
try:
|
|
|
|
|
|
return float(os.environ.get(name, default))
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return default
|
|
|
|
|
|
|
|
|
|
|
|
def _ensure_list(x) -> list:
|
|
|
|
|
|
if x is None: return []
|
|
|
|
|
|
if isinstance(x, list): return [str(i) for i in x]
|
|
|
|
|
|
if isinstance(x, (set, tuple)): return [str(i) for i in x]
|
|
|
|
|
|
return [str(x)]
|
|
|
|
|
|
|
|
|
|
|
|
def _load_types_config(types_cfg_explicit: Optional[dict] = None) -> dict:
|
|
|
|
|
|
"""Types-Registry *optional* einspeisen (bereits geparst), sonst lazy-laden vermeiden."""
|
|
|
|
|
|
return types_cfg_explicit or {}
|
|
|
|
|
|
|
2025-11-11 17:01:19 +01:00
|
|
|
|
def _text_from_note(note: Dict[str, Any]) -> str:
|
2025-11-11 16:58:22 +01:00
|
|
|
|
# Erwartete Inputs (siehe parser.py / import_markdown.py):
|
|
|
|
|
|
# note["body"] oder note["text"]; Fallback leerer String
|
|
|
|
|
|
return note.get("body") or note.get("text") or ""
|
|
|
|
|
|
|
|
|
|
|
|
def _iter_chunks(note: Dict[str, Any], chunk_profile: str, fulltext: str) -> List[Dict[str, Any]]:
|
2025-11-11 17:01:19 +01:00
|
|
|
|
"""Nutze bestehenden assemble_chunks(note_id, body, type)."""
|
2025-11-11 16:58:22 +01:00
|
|
|
|
note_id = note.get("id") or (note.get("frontmatter") or {}).get("id")
|
|
|
|
|
|
ntype = (note.get("frontmatter") or {}).get("type") or note.get("type") or "note"
|
|
|
|
|
|
# assemble_chunks liefert Liste von Dicts mit mindestens {"index","text"} (v1)
|
|
|
|
|
|
return assemble_chunks(note_id, fulltext, ntype)
|
|
|
|
|
|
|
2025-11-11 17:01:19 +01:00
|
|
|
|
def make_chunk_payloads(
|
|
|
|
|
|
note: Any,
|
|
|
|
|
|
path_arg: Optional[str] = None,
|
|
|
|
|
|
chunks_from_chunker: Optional[List[Dict[str, Any]]] = None,
|
|
|
|
|
|
*,
|
|
|
|
|
|
file_path: Optional[str] = None,
|
|
|
|
|
|
note_text: Optional[str] = None,
|
|
|
|
|
|
types_cfg: Optional[dict] = None,
|
|
|
|
|
|
) -> List[Dict[str, Any]]:
|
2025-11-11 16:58:22 +01:00
|
|
|
|
"""
|
|
|
|
|
|
Erzeugt Chunk-Payloads. Erwartet:
|
|
|
|
|
|
- `note`: Normalisierte Note-Struktur (inkl. frontmatter)
|
2025-11-11 17:01:19 +01:00
|
|
|
|
- `path_arg` oder `file_path`: Pfad der Note
|
2025-11-11 16:58:22 +01:00
|
|
|
|
- `chunks_from_chunker`: optional: Ergebnis von assemble_chunks (sonst wird intern erzeugt)
|
|
|
|
|
|
|
|
|
|
|
|
Rückgabe: Liste aus Payload-Dicts, jedes mit mind.:
|
|
|
|
|
|
- note_id, chunk_id, index, ord (Alias), title, type, path, text, retriever_weight, chunk_profile
|
|
|
|
|
|
- optional: tags (aus Note-FM), chunk_num, Chunk_Nummer (Aliases von index/ord)
|
|
|
|
|
|
"""
|
2025-11-09 10:11:34 +01:00
|
|
|
|
n = _as_dict(note)
|
2025-11-09 10:17:04 +01:00
|
|
|
|
fm = n.get("frontmatter") or {}
|
2025-11-09 10:11:34 +01:00
|
|
|
|
note_type = str(fm.get("type") or n.get("type") or "note")
|
2025-11-11 16:58:22 +01:00
|
|
|
|
types_cfg = _load_types_config(types_cfg)
|
2025-11-09 09:51:05 +01:00
|
|
|
|
|
2025-11-11 16:58:22 +01:00
|
|
|
|
cfg_for_type = types_cfg.get(note_type, {}) if isinstance(types_cfg, dict) else {}
|
|
|
|
|
|
default_rw = _env_float("MINDNET_DEFAULT_RETRIEVER_WEIGHT", 1.0)
|
2025-11-09 09:51:05 +01:00
|
|
|
|
|
2025-11-09 10:17:04 +01:00
|
|
|
|
retriever_weight = _coalesce(fm.get("retriever_weight"), cfg_for_type.get("retriever_weight"), default_rw)
|
2025-11-09 10:11:34 +01:00
|
|
|
|
try:
|
|
|
|
|
|
retriever_weight = float(retriever_weight)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
retriever_weight = default_rw
|
|
|
|
|
|
|
2025-11-09 10:17:04 +01:00
|
|
|
|
chunk_profile = _coalesce(fm.get("chunk_profile"), cfg_for_type.get("chunk_profile"), os.environ.get("MINDNET_DEFAULT_CHUNK_PROFILE","medium"))
|
|
|
|
|
|
chunk_profile = chunk_profile if isinstance(chunk_profile, str) else "medium"
|
2025-11-09 10:11:34 +01:00
|
|
|
|
|
|
|
|
|
|
note_id = n.get("note_id") or n.get("id") or fm.get("id")
|
|
|
|
|
|
title = n.get("title") or fm.get("title") or ""
|
2025-11-11 17:01:19 +01:00
|
|
|
|
# Pfad-Auflösung: Priorität file_path > note['path'] > path_arg
|
|
|
|
|
|
path = file_path or n.get("path") or path_arg
|
2025-11-09 10:11:34 +01:00
|
|
|
|
if isinstance(path, pathlib.Path):
|
|
|
|
|
|
path = str(path)
|
2025-11-11 16:58:22 +01:00
|
|
|
|
path = path or "" # garantiert vorhanden
|
2025-11-09 10:11:34 +01:00
|
|
|
|
|
2025-11-11 16:58:22 +01:00
|
|
|
|
# Denormalisierte Tags (optional): auf Chunks spiegeln, wenn vorhanden
|
|
|
|
|
|
tags = fm.get("tags") or fm.get("keywords") or n.get("tags")
|
|
|
|
|
|
tags_list = _ensure_list(tags) if tags else []
|
|
|
|
|
|
|
|
|
|
|
|
# Quelltext
|
2025-11-11 17:01:19 +01:00
|
|
|
|
fulltext = note_text if isinstance(note_text, str) else _text_from_note(n)
|
2025-11-11 16:58:22 +01:00
|
|
|
|
|
|
|
|
|
|
# Chunks besorgen
|
|
|
|
|
|
chunks = chunks_from_chunker if isinstance(chunks_from_chunker, list) else _iter_chunks(n, chunk_profile, fulltext)
|
2025-11-09 10:11:34 +01:00
|
|
|
|
|
|
|
|
|
|
payloads: List[Dict[str, Any]] = []
|
|
|
|
|
|
for c in chunks:
|
|
|
|
|
|
idx = c.get("index", len(payloads))
|
|
|
|
|
|
text = c.get("text") if isinstance(c, dict) else (str(c) if c is not None else "")
|
2025-11-09 10:17:04 +01:00
|
|
|
|
text = text if isinstance(text, str) else str(text or "")
|
2025-11-09 10:11:34 +01:00
|
|
|
|
|
2025-11-11 16:58:22 +01:00
|
|
|
|
# deterministische ID (unter Beibehaltung deines bisherigen Schemas)
|
2025-11-09 10:11:34 +01:00
|
|
|
|
key = f"{note_id}|{idx}"
|
2025-11-09 10:17:04 +01:00
|
|
|
|
h = hashlib.sha1(key.encode("utf-8")).hexdigest()[:12] if note_id else hashlib.sha1(f"{path}|{idx}".encode("utf-8")).hexdigest()[:12]
|
|
|
|
|
|
chunk_id = f"{note_id}-{idx:03d}-{h}" if note_id else f"{h}"
|
2025-11-09 10:11:34 +01:00
|
|
|
|
|
|
|
|
|
|
payload = {
|
|
|
|
|
|
"note_id": note_id,
|
|
|
|
|
|
"chunk_id": chunk_id,
|
|
|
|
|
|
"index": idx,
|
2025-11-11 16:58:22 +01:00
|
|
|
|
"ord": idx, # Alias für v2‑Schema
|
|
|
|
|
|
"chunk_num": idx, # neutraler Alias
|
2025-11-11 17:01:19 +01:00
|
|
|
|
"Chunk_Nummer": idx, # deutschsprachiger Alias
|
2025-11-09 10:11:34 +01:00
|
|
|
|
"title": title,
|
|
|
|
|
|
"type": note_type,
|
2025-11-11 16:58:22 +01:00
|
|
|
|
"path": path, # garantiert vorhanden
|
2025-11-11 17:01:19 +01:00
|
|
|
|
"text": text, # nie leer
|
2025-11-09 10:11:34 +01:00
|
|
|
|
"retriever_weight": retriever_weight,
|
|
|
|
|
|
"chunk_profile": chunk_profile,
|
|
|
|
|
|
}
|
2025-11-11 16:58:22 +01:00
|
|
|
|
if tags_list:
|
|
|
|
|
|
payload["tags"] = tags_list
|
|
|
|
|
|
|
|
|
|
|
|
# JSON‑Roundtrip als einfache Validierung
|
2025-11-09 10:11:34 +01:00
|
|
|
|
json.loads(json.dumps(payload, ensure_ascii=False))
|
|
|
|
|
|
payloads.append(payload)
|
|
|
|
|
|
|
|
|
|
|
|
return payloads
|