mindnet/app/core/note_payload.py

199 lines
6.9 KiB
Python
Raw Normal View History

2025-09-09 11:05:32 +02:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Modul: app/core/note_payload.py
2025-09-09 11:27:18 +02:00
Version: 1.4.0
2025-09-09 11:05:32 +02:00
Datum: 2025-09-09
Kurzbeschreibung
----------------
Erzeugt den Qdrant-Payload für **Notes**. Neben stabiler Hash-Bildung zur
Idempotenz wird der vollständige Body unter ``fulltext`` persistiert und
der Dateipfad relativ zum Vault gespeichert. Das erlaubt eine verlustfreie
Rekonstruktion im Export (erst ``fulltext``, sonst Chunks).
2025-09-09 11:27:18 +02:00
Hash-Steuerung
--------------
- Modus: ``body`` (Default) | ``frontmatter`` | ``body+frontmatter``
* per Funktionsparameter ``hash_mode`` (prio 1)
* oder ENV ``MINDNET_HASH_MODE`` (prio 2)
- Normalisierung: ``canonical`` (Default) | ``none``
* per Funktionsparameter ``hash_normalize`` (prio 1)
* oder ENV ``MINDNET_HASH_NORMALIZE`` (prio 2)
2025-09-09 11:05:32 +02:00
Beispiele (CLI – Sichtprüfung)
------------------------------
python3 -m app.core.note_payload --from-file ./vault/demo.md --vault-root ./vault --print
"""
2025-09-08 12:22:05 +02:00
2025-09-02 19:51:47 +02:00
from __future__ import annotations
2025-09-09 11:05:32 +02:00
import argparse
2025-09-02 19:51:47 +02:00
import hashlib
2025-09-08 12:22:05 +02:00
import json
import os
2025-09-08 12:42:51 +02:00
from typing import Any, Dict, Optional
2025-09-08 12:22:05 +02:00
2025-09-09 11:05:32 +02:00
try:
2025-09-09 11:15:01 +02:00
from app.core.parser import read_markdown, extract_wikilinks
2025-09-09 11:05:32 +02:00
except Exception: # pragma: no cover
2025-09-09 11:15:01 +02:00
from .parser import read_markdown, extract_wikilinks # type: ignore
2025-09-08 12:22:05 +02:00
2025-09-09 11:05:32 +02:00
# ---------------------------------------------------------------------------
# Hashing
# ---------------------------------------------------------------------------
2025-09-08 12:22:05 +02:00
2025-09-09 11:05:32 +02:00
def _canon_frontmatter(fm: Dict[str, Any]) -> str:
"""Kanonische, stabile JSON-Serialisierung der Frontmatter für Hashbildung."""
return json.dumps(fm or {}, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
2025-09-08 12:22:05 +02:00
2025-09-09 11:27:18 +02:00
def _normalize_body(body: str, mode: str) -> str:
"""Normalisiert den Body für reproduzierbare Hashes (oder nicht)."""
if mode == "none":
return body if body is not None else ""
# canonical: \r\n→\n, trailing spaces, mehrfach-blankzeilen trimmen
text = (body or "").replace("\r\n", "\n").replace("\r", "\n")
# trailing whitespace am Zeilenende entfernen
text = "\n".join(line.rstrip() for line in text.split("\n"))
# keine aggressivere Logik (keine inhaltliche Änderung)
return text
def compute_hash(
*,
body: Optional[str],
frontmatter: Optional[Dict[str, Any]],
mode: Optional[str] = None,
normalize: Optional[str] = None,
) -> str:
2025-09-08 12:22:05 +02:00
"""
2025-09-09 11:27:18 +02:00
Berechnet einen Hex-Hash gemäß ``mode`` und ``normalize``.
2025-09-08 12:22:05 +02:00
2025-09-09 11:05:32 +02:00
mode:
- "body" (Default)
- "frontmatter"
- "body+frontmatter"
2025-09-09 11:27:18 +02:00
normalize:
- "canonical" (Default)
- "none"
2025-09-08 12:22:05 +02:00
"""
2025-09-09 11:15:01 +02:00
mode = (mode or os.environ.get("MINDNET_HASH_MODE", "body")).strip().lower()
2025-09-09 11:27:18 +02:00
normalize = (normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical")).strip().lower()
body = _normalize_body(body or "", normalize)
2025-09-09 11:05:32 +02:00
fm_s = _canon_frontmatter(frontmatter or {})
h = hashlib.sha256()
if mode == "frontmatter":
h.update(fm_s.encode("utf-8"))
elif mode == "body+frontmatter":
h.update(body.encode("utf-8"))
h.update(b"\n--FM--\n")
h.update(fm_s.encode("utf-8"))
else: # body
h.update(body.encode("utf-8"))
return h.hexdigest()
# ---------------------------------------------------------------------------
# Kernfunktion
# ---------------------------------------------------------------------------
2025-09-08 12:22:05 +02:00
2025-09-09 11:27:18 +02:00
def make_note_payload(
parsed: Any,
vault_root: Optional[str] = None,
*,
hash_mode: Optional[str] = None,
hash_normalize: Optional[str] = None,
) -> Dict[str, Any]:
2025-09-08 12:22:05 +02:00
"""
2025-09-09 11:05:32 +02:00
Erzeugt den Payload für eine geparste Note.
Parameters
----------
parsed : Any
Objekt mit Attributen/Keys ``frontmatter``, ``body``, ``path``.
vault_root : Optional[str]
Vault-Wurzel (für Pfad-Relativierung). Wenn ``None``, wird ``path`` unverändert übernommen.
2025-09-09 11:27:18 +02:00
hash_mode : Optional[str]
"body" | "frontmatter" | "body+frontmatter" (überschreibt ENV).
hash_normalize : Optional[str]
"canonical" | "none" (überschreibt ENV).
2025-09-09 11:05:32 +02:00
Returns
-------
Dict[str, Any]
Qdrant-Payload für die Notes-Collection.
2025-09-08 12:22:05 +02:00
"""
2025-09-09 11:05:32 +02:00
# "Duck typing": dict oder Objekt akzeptieren
2025-09-09 11:15:01 +02:00
fm = (
getattr(parsed, "frontmatter", None)
or getattr(parsed, "fm", None)
or getattr(parsed, "front_matter", None)
or (parsed.get("frontmatter") if isinstance(parsed, dict) else {})
) or {}
body = getattr(parsed, "body", None) or (parsed.get("body") if isinstance(parsed, dict) else "") or ""
path = getattr(parsed, "path", None) or (parsed.get("path") if isinstance(parsed, dict) else "") or ""
2025-09-08 12:22:05 +02:00
2025-09-09 11:27:18 +02:00
# Hash gem. Modus bilden
hash_fulltext = compute_hash(body=body, frontmatter=fm, mode=hash_mode, normalize=hash_normalize)
2025-09-08 12:22:05 +02:00
2025-09-09 11:05:32 +02:00
# Pfad relativieren
rel_path = path
try:
if vault_root:
rel = os.path.relpath(path, vault_root)
rel = rel.replace("\\", "/").lstrip("/") # normalisieren
rel_path = rel
except Exception:
2025-09-09 11:27:18 +02:00
pass # Pfad nicht kritisch für Hash/ID
2025-09-09 11:05:32 +02:00
# Optionale Note-Level-Wikilinks (Fallback, wenn Chunks nicht geliefert werden)
note_level_refs = list(dict.fromkeys(extract_wikilinks(body))) if body else []
2025-09-08 12:22:05 +02:00
payload: Dict[str, Any] = {
2025-09-09 11:15:01 +02:00
"note_id": fm.get("id") or fm.get("note_id"),
"title": fm.get("title"),
"type": fm.get("type"),
"status": fm.get("status"),
"created": fm.get("created"),
"updated": fm.get("updated"),
"path": rel_path or fm.get("path"),
"tags": fm.get("tags"),
2025-09-08 12:22:05 +02:00
"hash_fulltext": hash_fulltext,
2025-09-09 11:27:18 +02:00
# Volltext persistieren (verlustfreie Rekonstruktion)
2025-09-09 11:05:32 +02:00
"fulltext": body,
2025-09-09 11:27:18 +02:00
# Fallback-Refs auf Note-Ebene
2025-09-09 11:05:32 +02:00
"references": note_level_refs,
2025-09-08 12:22:05 +02:00
}
2025-09-09 11:05:32 +02:00
for k in ("area", "project", "source", "lang", "slug"):
2025-09-09 11:15:01 +02:00
if k in fm:
2025-09-08 12:22:05 +02:00
payload[k] = fm[k]
return payload
2025-09-09 11:05:32 +02:00
# ---------------------------------------------------------------------------
# CLI – Sichtprüfung
# ---------------------------------------------------------------------------
def _cli() -> None:
ap = argparse.ArgumentParser(description="Note-Payload aus Markdown erzeugen und anzeigen")
ap.add_argument("--from-file", dest="src", required=True, help="Pfad zur Markdown-Datei")
ap.add_argument("--vault-root", dest="vault_root", default=None, help="Vault-Wurzel zur Pfad-Relativierung")
ap.add_argument("--print", dest="do_print", action="store_true", help="Payload auf stdout ausgeben")
2025-09-09 11:27:18 +02:00
ap.add_argument("--hash-mode", choices=["body", "frontmatter", "body+frontmatter"], default=None)
ap.add_argument("--hash-normalize", choices=["canonical", "none"], default=None)
2025-09-09 11:05:32 +02:00
args = ap.parse_args()
2025-09-09 11:15:01 +02:00
parsed = read_markdown(args.src)
2025-09-09 11:27:18 +02:00
payload = make_note_payload(parsed, vault_root=args.vault_root,
hash_mode=args.hash_mode, hash_normalize=args.hash_normalize)
2025-09-09 11:05:32 +02:00
if args.do_print:
print(json.dumps(payload, ensure_ascii=False, indent=2))
2025-09-08 12:42:51 +02:00
2025-09-09 11:05:32 +02:00
if __name__ == "__main__": # pragma: no cover
_cli()