2025-11-08 16:18:31 +01:00
|
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
"""
|
2025-11-16 18:47:36 +01:00
|
|
|
|
scripts/import_markdown.py (Mindnet V2 — Importer, v2.5.2)
|
|
|
|
|
|
|
|
|
|
|
|
Änderungen in 2.5.2 (minimal & gezielt)
|
|
|
|
|
|
---------------------------------------
|
|
|
|
|
|
- **Explizite Spiegelung** von `chunk_profile` in Note- und Chunk-Payload:
|
|
|
|
|
|
note_pl["chunk_profile"] = fm.get("chunk_profile"); für jeden Chunk cpl["chunk_profile"] = fm.get("chunk_profile").
|
|
|
|
|
|
- **Explizite Spiegelung** von `retriever_weight` in jedem Chunk (falls Builder es nicht gesetzt hat).
|
|
|
|
|
|
- **Feld-basierte Change-Erkennung** erweitert:
|
|
|
|
|
|
Wenn bestehende Note-Payload (`old_payload`) bei `retriever_weight` oder `chunk_profile` vom neuen Wert abweicht
|
|
|
|
|
|
oder ein Feld fehlt, wird `changed = True` gesetzt → Upsert erzwingen.
|
|
|
|
|
|
- **Robuste Übergabe** von Type-Registry an Chunk-Builder:
|
|
|
|
|
|
`types_cfg=(reg.get('types') or reg or {})` – damit greifen Resolver in chunk_payload.py sicher auf `types.yaml` zu.
|
2025-11-08 16:18:31 +01:00
|
|
|
|
"""
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
|
|
import json
|
|
|
|
|
|
import os
|
|
|
|
|
|
import sys
|
|
|
|
|
|
from typing import Dict, List, Optional, Tuple, Any, Set
|
|
|
|
|
|
|
|
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
|
|
from qdrant_client.http import models as rest
|
2025-11-16 18:16:29 +01:00
|
|
|
|
import yaml
|
2025-11-08 16:18:31 +01:00
|
|
|
|
|
2025-11-11 17:19:22 +01:00
|
|
|
|
# --- Projekt-Imports ---
|
2025-11-16 18:16:29 +01:00
|
|
|
|
from app.core.parser import read_markdown, normalize_frontmatter, validate_required_frontmatter
|
2025-11-08 16:18:31 +01:00
|
|
|
|
from app.core.note_payload import make_note_payload
|
2025-11-11 17:19:22 +01:00
|
|
|
|
from app.core.chunker import assemble_chunks
|
2025-11-08 16:18:31 +01:00
|
|
|
|
from app.core.chunk_payload import make_chunk_payloads
|
|
|
|
|
|
try:
|
|
|
|
|
|
from app.core.derive_edges import build_edges_for_note
|
2025-11-16 18:47:36 +01:00
|
|
|
|
except Exception:
|
2025-11-08 16:18:31 +01:00
|
|
|
|
from app.core.edges import build_edges_for_note # type: ignore
|
2025-11-16 18:16:29 +01:00
|
|
|
|
from app.core.qdrant import QdrantConfig, get_client, ensure_collections, ensure_payload_indexes
|
|
|
|
|
|
from app.core.qdrant_points import points_for_chunks, points_for_note, points_for_edges, upsert_batch
|
|
|
|
|
|
|
|
|
|
|
|
# embeddings optional
|
2025-11-08 16:18:31 +01:00
|
|
|
|
try:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
from app.core.embed import embed_texts # optional
|
2025-11-16 18:47:36 +01:00
|
|
|
|
except Exception:
|
2025-11-16 18:16:29 +01:00
|
|
|
|
embed_texts = None # type: ignore
|
2025-11-08 18:22:28 +01:00
|
|
|
|
|
2025-11-16 18:16:29 +01:00
|
|
|
|
|
|
|
|
|
|
# ============================================================
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Type-Registry
|
2025-11-16 18:16:29 +01:00
|
|
|
|
# ============================================================
|
2025-11-10 12:20:09 +01:00
|
|
|
|
|
|
|
|
|
|
def _env(name: str, default: Optional[str] = None) -> str:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
v = os.getenv(name)
|
|
|
|
|
|
return v if v is not None else (default or "")
|
2025-11-08 18:22:28 +01:00
|
|
|
|
|
2025-11-16 18:16:29 +01:00
|
|
|
|
def _deep_get(root: Any, path: str) -> Any:
|
|
|
|
|
|
cur = root
|
|
|
|
|
|
for key in path.split("."):
|
|
|
|
|
|
if not isinstance(cur, dict) or key not in cur:
|
|
|
|
|
|
return None
|
|
|
|
|
|
cur = cur[key]
|
|
|
|
|
|
return cur
|
|
|
|
|
|
|
|
|
|
|
|
def _as_float(x: Any) -> Optional[float]:
|
|
|
|
|
|
try:
|
|
|
|
|
|
return float(x)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
2025-11-11 17:19:22 +01:00
|
|
|
|
def load_type_registry() -> dict:
|
|
|
|
|
|
path = _env("MINDNET_TYPES_FILE", "./config/types.yaml")
|
|
|
|
|
|
if not os.path.isfile(path):
|
|
|
|
|
|
return {}
|
2025-11-08 18:22:28 +01:00
|
|
|
|
try:
|
2025-11-10 12:20:09 +01:00
|
|
|
|
with open(path, "r", encoding="utf-8") as f:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
return yaml.safe_load(f) or {}
|
2025-11-08 18:22:28 +01:00
|
|
|
|
except Exception:
|
2025-11-08 18:13:07 +01:00
|
|
|
|
return {}
|
2025-11-10 12:20:09 +01:00
|
|
|
|
|
2025-11-11 17:19:22 +01:00
|
|
|
|
def get_type_config(note_type: Optional[str], reg: dict) -> dict:
|
|
|
|
|
|
if not note_type or not isinstance(reg, dict):
|
|
|
|
|
|
return {}
|
|
|
|
|
|
types = reg.get("types", {}) if isinstance(reg.get("types"), dict) else {}
|
|
|
|
|
|
return types.get(note_type, {}) if isinstance(types, dict) else {}
|
|
|
|
|
|
|
|
|
|
|
|
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
|
|
|
|
|
|
if requested and isinstance(requested, str):
|
|
|
|
|
|
return requested
|
|
|
|
|
|
types = reg.get("types", {}) if isinstance(reg.get("types"), dict) else {}
|
|
|
|
|
|
return "concept" if "concept" in types else (requested or "concept")
|
|
|
|
|
|
|
|
|
|
|
|
def effective_chunk_profile(note_type: str, reg: dict) -> Optional[str]:
|
|
|
|
|
|
cfg = get_type_config(note_type, reg)
|
|
|
|
|
|
prof = cfg.get("chunk_profile")
|
|
|
|
|
|
if isinstance(prof, str):
|
|
|
|
|
|
return prof
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
2025-11-16 18:16:29 +01:00
|
|
|
|
def effective_retriever_weight_from_registry(note_type: str, reg: dict) -> Tuple[Optional[float], Optional[str]]:
|
|
|
|
|
|
candidates = [
|
|
|
|
|
|
f"types.{note_type}.retriever_weight",
|
|
|
|
|
|
f"types.{note_type}.retriever.weight",
|
|
|
|
|
|
f"types.{note_type}.retrieval.weight",
|
|
|
|
|
|
"defaults.retriever_weight",
|
|
|
|
|
|
"defaults.retriever.weight",
|
|
|
|
|
|
"global.retriever_weight",
|
|
|
|
|
|
"global.retriever.weight",
|
|
|
|
|
|
]
|
|
|
|
|
|
for path in candidates:
|
|
|
|
|
|
val = _deep_get(reg, path)
|
|
|
|
|
|
v = _as_float(val)
|
|
|
|
|
|
if v is not None:
|
|
|
|
|
|
return v, path
|
|
|
|
|
|
return None, None
|
|
|
|
|
|
|
|
|
|
|
|
def compute_effective_retriever_weight(fm: Dict[str, Any], note_type: str, reg: dict) -> Tuple[float, str]:
|
2025-11-16 18:07:56 +01:00
|
|
|
|
if fm.get("retriever_weight") is not None:
|
2025-11-16 18:16:29 +01:00
|
|
|
|
v = _as_float(fm.get("retriever_weight"))
|
|
|
|
|
|
if v is not None:
|
|
|
|
|
|
return v, "frontmatter.retriever_weight"
|
|
|
|
|
|
r, rpath = effective_retriever_weight_from_registry(note_type, reg)
|
2025-11-16 18:07:56 +01:00
|
|
|
|
if r is not None:
|
2025-11-16 18:16:29 +01:00
|
|
|
|
return float(r), f"types.yaml:{rpath}"
|
|
|
|
|
|
return 1.0, "default:1.0"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ============================================================
|
|
|
|
|
|
# Qdrant Helpers
|
|
|
|
|
|
# ============================================================
|
2025-11-11 17:19:22 +01:00
|
|
|
|
|
|
|
|
|
|
def collections(prefix: str) -> Tuple[str, str, str]:
|
|
|
|
|
|
return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges"
|
|
|
|
|
|
|
|
|
|
|
|
def fetch_existing_note_payload(client, prefix: str, note_id: str) -> Optional[Dict]:
|
|
|
|
|
|
notes_col, _, _ = collections(prefix)
|
|
|
|
|
|
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
2025-11-16 18:47:36 +01:00
|
|
|
|
points, _ = client.scroll(collection_name=notes_col, scroll_filter=f, with_payload=True, with_vectors=False, limit=1)
|
2025-11-11 17:19:22 +01:00
|
|
|
|
if not points:
|
2025-11-08 16:18:31 +01:00
|
|
|
|
return None
|
2025-11-11 17:19:22 +01:00
|
|
|
|
return points[0].payload or {}
|
2025-11-08 16:18:31 +01:00
|
|
|
|
|
|
|
|
|
|
def list_qdrant_note_ids(client, prefix: str) -> Set[str]:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
notes_col, _, _ = collections(prefix)
|
2025-11-08 16:18:31 +01:00
|
|
|
|
out: Set[str] = set()
|
2025-11-11 17:19:22 +01:00
|
|
|
|
next_page = None
|
2025-11-08 16:18:31 +01:00
|
|
|
|
while True:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
pts, next_page = client.scroll(collection_name=notes_col, with_payload=True, with_vectors=False, limit=256, offset=next_page)
|
2025-11-11 17:19:22 +01:00
|
|
|
|
if not pts:
|
|
|
|
|
|
break
|
2025-11-08 16:18:31 +01:00
|
|
|
|
for p in pts:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
pl = p.payload or {}
|
|
|
|
|
|
nid = pl.get("note_id")
|
2025-11-08 16:18:31 +01:00
|
|
|
|
if isinstance(nid, str):
|
|
|
|
|
|
out.add(nid)
|
2025-11-11 17:19:22 +01:00
|
|
|
|
if next_page is None:
|
2025-11-08 16:18:31 +01:00
|
|
|
|
break
|
|
|
|
|
|
return out
|
|
|
|
|
|
|
2025-11-10 12:20:09 +01:00
|
|
|
|
def purge_note_artifacts(client, prefix: str, note_id: str) -> None:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
_, chunks_col, edges_col = collections(prefix)
|
|
|
|
|
|
filt = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
|
|
|
|
for col in (chunks_col, edges_col):
|
|
|
|
|
|
try:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
client.delete(collection_name=col, points_selector=rest.FilterSelector(filter=filt), wait=True)
|
2025-11-11 17:19:22 +01:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(json.dumps({"note_id": note_id, "warn": f"delete in {col} via filter failed: {e}"}))
|
2025-11-09 10:42:55 +01:00
|
|
|
|
|
2025-11-10 12:20:09 +01:00
|
|
|
|
def delete_note_everywhere(client, prefix: str, note_id: str) -> None:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
notes_col, chunks_col, edges_col = collections(prefix)
|
|
|
|
|
|
filt = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
|
|
|
|
for col in (edges_col, chunks_col, notes_col):
|
|
|
|
|
|
try:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
client.delete(collection_name=col, points_selector=rest.FilterSelector(filter=filt), wait=True)
|
2025-11-11 17:19:22 +01:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(json.dumps({"note_id": note_id, "warn": f"delete in {col} failed: {e}"}))
|
|
|
|
|
|
|
|
|
|
|
|
def _has_any_point(client, collection: str, note_id: str) -> bool:
|
|
|
|
|
|
filt = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
2025-11-16 18:47:36 +01:00
|
|
|
|
pts, _ = client.scroll(collection_name=collection, scroll_filter=filt, with_payload=False, with_vectors=False, limit=1)
|
2025-11-11 17:19:22 +01:00
|
|
|
|
return bool(pts)
|
|
|
|
|
|
|
|
|
|
|
|
def artifacts_missing(client, prefix: str, note_id: str) -> Tuple[bool, bool]:
|
|
|
|
|
|
_, chunks_col, edges_col = collections(prefix)
|
|
|
|
|
|
chunks_missing = not _has_any_point(client, chunks_col, note_id)
|
|
|
|
|
|
edges_missing = not _has_any_point(client, edges_col, note_id)
|
|
|
|
|
|
return chunks_missing, edges_missing
|
|
|
|
|
|
|
2025-11-16 18:16:29 +01:00
|
|
|
|
|
|
|
|
|
|
# ============================================================
|
2025-11-11 17:19:22 +01:00
|
|
|
|
# Main
|
2025-11-16 18:16:29 +01:00
|
|
|
|
# ============================================================
|
|
|
|
|
|
|
2025-11-11 17:19:22 +01:00
|
|
|
|
def _resolve_mode(m: Optional[str]) -> str:
|
|
|
|
|
|
m = (m or "body").strip().lower()
|
|
|
|
|
|
return m if m in {"body", "frontmatter", "full"} else "body"
|
2025-11-08 18:22:28 +01:00
|
|
|
|
|
2025-11-08 14:25:31 +01:00
|
|
|
|
def main() -> None:
|
2025-11-08 15:25:18 +01:00
|
|
|
|
load_dotenv()
|
2025-11-08 18:22:28 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
ap = argparse.ArgumentParser(prog="scripts.import_markdown", description="Importiert Markdown-Notizen in Qdrant (Notes/Chunks/Edges).")
|
|
|
|
|
|
ap.add_argument("--vault", required=True)
|
|
|
|
|
|
ap.add_argument("--only-path")
|
|
|
|
|
|
ap.add_argument("--apply", action="store_true")
|
|
|
|
|
|
ap.add_argument("--purge-before-upsert", action="store_true")
|
|
|
|
|
|
ap.add_argument("--force-replace", action="store_true")
|
|
|
|
|
|
ap.add_argument("--note-id")
|
|
|
|
|
|
ap.add_argument("--note-scope-refs", action="store_true")
|
|
|
|
|
|
ap.add_argument("--hash-mode")
|
|
|
|
|
|
ap.add_argument("--hash-source")
|
|
|
|
|
|
ap.add_argument("--hash-normalize")
|
|
|
|
|
|
ap.add_argument("--compare-text", action="store_true")
|
|
|
|
|
|
ap.add_argument("--baseline-modes", action="store_true")
|
|
|
|
|
|
ap.add_argument("--sync-deletes", action="store_true")
|
|
|
|
|
|
ap.add_argument("--prefix")
|
2025-11-08 15:25:18 +01:00
|
|
|
|
args = ap.parse_args()
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
mode = _resolve_mode(args.hash_mode)
|
|
|
|
|
|
src = _env("MINDNET_HASH_SOURCE", args.hash_source or "parsed")
|
|
|
|
|
|
norm = _env("MINDNET_HASH_NORMALIZE", args.hash_normalize or "canonical")
|
2025-11-11 17:19:22 +01:00
|
|
|
|
note_scope_refs_env = (_env("MINDNET_NOTE_SCOPE_REFS", "false") == "true")
|
2025-11-08 17:00:27 +01:00
|
|
|
|
note_scope_refs = args.note_scope_refs or note_scope_refs_env
|
2025-11-11 17:19:22 +01:00
|
|
|
|
compare_text = args.compare_text or (_env("MINDNET_COMPARE_TEXT", "false") == "true")
|
2025-11-08 15:25:18 +01:00
|
|
|
|
|
2025-11-08 14:25:31 +01:00
|
|
|
|
cfg = QdrantConfig.from_env()
|
2025-11-08 15:25:18 +01:00
|
|
|
|
if args.prefix:
|
|
|
|
|
|
cfg.prefix = args.prefix.strip()
|
2025-11-08 08:31:49 +01:00
|
|
|
|
client = get_client(cfg)
|
2025-11-08 17:00:27 +01:00
|
|
|
|
ensure_collections(client, cfg.prefix, cfg.dim)
|
|
|
|
|
|
ensure_payload_indexes(client, cfg.prefix)
|
2025-11-08 15:25:18 +01:00
|
|
|
|
|
2025-11-08 18:22:28 +01:00
|
|
|
|
reg = load_type_registry()
|
2025-11-16 18:47:36 +01:00
|
|
|
|
types_cfg_node = reg.get("types") if isinstance(reg, dict) else {}
|
2025-11-08 18:13:07 +01:00
|
|
|
|
|
2025-11-08 15:25:18 +01:00
|
|
|
|
root = os.path.abspath(args.vault)
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Datei-Liste
|
2025-11-08 15:25:18 +01:00
|
|
|
|
if args.only_path:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
files = [os.path.abspath(args.only_path)]
|
2025-11-08 15:25:18 +01:00
|
|
|
|
else:
|
2025-11-16 18:16:29 +01:00
|
|
|
|
files: List[str] = []
|
|
|
|
|
|
for dirpath, _, filenames in os.walk(root):
|
|
|
|
|
|
for fn in filenames:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
if fn.lower().endswith(".md"):
|
|
|
|
|
|
p = os.path.join(dirpath, fn)
|
|
|
|
|
|
pn = p.replace("\\", "/")
|
|
|
|
|
|
if any(ex in pn for ex in ["/.obsidian/", "/_backup_frontmatter/", "/_imported/"]):
|
|
|
|
|
|
continue
|
|
|
|
|
|
files.append(p)
|
2025-11-16 18:16:29 +01:00
|
|
|
|
files.sort()
|
2025-11-08 15:25:18 +01:00
|
|
|
|
if not files:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
print("Keine Markdown-Dateien gefunden.", file=sys.stderr)
|
2025-11-08 15:25:18 +01:00
|
|
|
|
sys.exit(2)
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Optional: Sync-Deletes
|
2025-11-08 15:25:18 +01:00
|
|
|
|
if args.sync_deletes:
|
|
|
|
|
|
vault_note_ids: Set[str] = set()
|
|
|
|
|
|
for path in files:
|
|
|
|
|
|
try:
|
|
|
|
|
|
parsed = read_markdown(path)
|
|
|
|
|
|
if not parsed:
|
|
|
|
|
|
continue
|
|
|
|
|
|
fm = normalize_frontmatter(parsed.frontmatter)
|
|
|
|
|
|
nid = fm.get("id")
|
|
|
|
|
|
if isinstance(nid, str):
|
|
|
|
|
|
vault_note_ids.add(nid)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
continue
|
|
|
|
|
|
qdrant_note_ids = list_qdrant_note_ids(client, cfg.prefix)
|
|
|
|
|
|
to_delete = sorted(qdrant_note_ids - vault_note_ids)
|
2025-11-16 18:47:36 +01:00
|
|
|
|
print(json.dumps({"action":"sync-deletes","prefix":cfg.prefix,"qdrant_total":len(qdrant_note_ids),"vault_total":len(vault_note_ids),"to_delete_count":len(to_delete),"to_delete":to_delete[:50]+(["…"] if len(to_delete)>50 else [])}, ensure_ascii=False))
|
2025-11-08 15:25:18 +01:00
|
|
|
|
if args.apply and to_delete:
|
|
|
|
|
|
for nid in to_delete:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
print(json.dumps({"action":"delete","note_id":nid,"decision":"apply"}))
|
2025-11-08 15:25:18 +01:00
|
|
|
|
delete_note_everywhere(client, cfg.prefix, nid)
|
|
|
|
|
|
|
2025-11-11 17:19:22 +01:00
|
|
|
|
key_current = f"{mode}:{src}:{norm}"
|
|
|
|
|
|
processed = 0
|
2025-11-16 18:47:36 +01:00
|
|
|
|
|
2025-11-08 15:25:18 +01:00
|
|
|
|
for path in files:
|
|
|
|
|
|
try:
|
|
|
|
|
|
parsed = read_markdown(path)
|
2025-11-08 18:22:28 +01:00
|
|
|
|
if not parsed:
|
|
|
|
|
|
continue
|
2025-11-08 15:25:18 +01:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(json.dumps({"path": path, "error": f"read_markdown failed: {type(e).__name__}: {e}"}))
|
|
|
|
|
|
continue
|
2025-11-08 14:25:31 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Frontmatter
|
2025-11-08 15:25:18 +01:00
|
|
|
|
try:
|
|
|
|
|
|
fm = normalize_frontmatter(parsed.frontmatter)
|
|
|
|
|
|
validate_required_frontmatter(fm)
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(json.dumps({"path": path, "error": f"Frontmatter invalid: {type(e).__name__}: {e}"}))
|
2025-11-08 08:31:49 +01:00
|
|
|
|
continue
|
|
|
|
|
|
|
2025-11-08 15:25:18 +01:00
|
|
|
|
if args.note_id and not args.only_path and fm.get("id") != args.note_id:
|
|
|
|
|
|
continue
|
2025-11-08 08:31:49 +01:00
|
|
|
|
|
2025-11-08 15:25:18 +01:00
|
|
|
|
processed += 1
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Typ + Profile/Weight
|
|
|
|
|
|
note_type = resolve_note_type(fm.get("type"), reg)
|
2025-11-08 18:22:28 +01:00
|
|
|
|
fm["type"] = note_type or fm.get("type") or "concept"
|
|
|
|
|
|
prof = effective_chunk_profile(note_type, reg)
|
|
|
|
|
|
if prof:
|
2025-11-08 18:13:07 +01:00
|
|
|
|
fm["chunk_profile"] = prof
|
2025-11-16 18:16:29 +01:00
|
|
|
|
rw, rw_source = compute_effective_retriever_weight(fm, note_type, reg)
|
2025-11-16 18:47:36 +01:00
|
|
|
|
fm["retriever_weight"] = rw
|
2025-11-08 18:22:28 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Note-Payload
|
2025-11-08 18:22:28 +01:00
|
|
|
|
try:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
note_pl = make_note_payload(parsed, vault_root=root, hash_mode=mode, hash_normalize=norm, hash_source=src, file_path=path)
|
2025-11-08 18:22:28 +01:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(json.dumps({"path": path, "error": f"make_note_payload failed: {type(e).__name__}: {e}"}))
|
|
|
|
|
|
continue
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Explizites Spiegeln: chunk_profile & retriever_weight in Note
|
|
|
|
|
|
if fm.get("chunk_profile") is not None:
|
|
|
|
|
|
note_pl["chunk_profile"] = fm.get("chunk_profile")
|
|
|
|
|
|
note_pl["retriever_weight"] = float(rw) if isinstance(rw, (int, float)) else 1.0
|
2025-11-08 11:53:06 +01:00
|
|
|
|
|
2025-11-08 15:25:18 +01:00
|
|
|
|
note_id = note_pl.get("note_id") or fm.get("id")
|
|
|
|
|
|
if not note_id:
|
|
|
|
|
|
print(json.dumps({"path": path, "error": "Missing note_id after payload build"}))
|
|
|
|
|
|
continue
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Bestehende Note in Qdrant (für Changed-Detektion)
|
|
|
|
|
|
old_payload = fetch_existing_note_payload(client, cfg.prefix, note_id)
|
2025-11-08 15:25:18 +01:00
|
|
|
|
has_old = old_payload is not None
|
2025-11-11 17:19:22 +01:00
|
|
|
|
old_hashes = (old_payload or {}).get("hashes") or {}
|
|
|
|
|
|
old_hash_exact = old_hashes.get(key_current)
|
|
|
|
|
|
new_hash_exact = (note_pl.get("hashes") or {}).get(key_current)
|
|
|
|
|
|
needs_baseline = (old_hash_exact is None)
|
|
|
|
|
|
hash_changed = (old_hash_exact is not None and new_hash_exact is not None and old_hash_exact != new_hash_exact)
|
|
|
|
|
|
|
|
|
|
|
|
text_changed = False
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Optionaler Text-Vergleich (teuer)
|
|
|
|
|
|
# if compare_text:
|
|
|
|
|
|
# old_text = (old_payload or {}).get("fulltext") or ""
|
|
|
|
|
|
# new_text = note_pl.get("fulltext") or (getattr(parsed, "body", "") or "")
|
|
|
|
|
|
# text_changed = (old_text != new_text)
|
2025-11-08 15:25:18 +01:00
|
|
|
|
|
2025-11-11 17:19:22 +01:00
|
|
|
|
changed = args.force_replace or (not has_old) or hash_changed or text_changed
|
2025-11-16 18:47:36 +01:00
|
|
|
|
|
|
|
|
|
|
# Feld-basierte Change-Erkennung (erzwingt Update, wenn Werte nicht stimmen)
|
2025-11-16 18:44:46 +01:00
|
|
|
|
if has_old:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
if old_payload.get("retriever_weight") != note_pl.get("retriever_weight"):
|
|
|
|
|
|
changed = True
|
|
|
|
|
|
if old_payload.get("chunk_profile") != note_pl.get("chunk_profile"):
|
2025-11-16 18:44:46 +01:00
|
|
|
|
changed = True
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Chunks
|
2025-11-08 17:29:25 +01:00
|
|
|
|
try:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
body_text = getattr(parsed, "body", "") or ""
|
|
|
|
|
|
chunks = assemble_chunks(fm["id"], body_text, fm.get("type", "concept"))
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# WICHTIG: Note-Objekt mit verschachtelter FM + Registry an Chunk-Builder übergeben
|
2025-11-16 18:38:06 +01:00
|
|
|
|
chunk_note = {
|
|
|
|
|
|
"frontmatter": fm,
|
|
|
|
|
|
"id": fm.get("id"),
|
|
|
|
|
|
"type": fm.get("type"),
|
|
|
|
|
|
"title": fm.get("title"),
|
|
|
|
|
|
"path": note_pl.get("path") or path,
|
|
|
|
|
|
"note_id": note_pl.get("note_id"),
|
|
|
|
|
|
"tags": fm.get("tags"),
|
|
|
|
|
|
}
|
|
|
|
|
|
chunk_pls: List[Dict[str, Any]] = make_chunk_payloads(
|
|
|
|
|
|
chunk_note,
|
|
|
|
|
|
note_pl["path"],
|
|
|
|
|
|
chunks,
|
|
|
|
|
|
note_text=body_text,
|
2025-11-16 18:47:36 +01:00
|
|
|
|
types_cfg=(reg.get("types") if isinstance(reg, dict) and isinstance(reg.get("types"), dict) else reg if isinstance(reg, dict) else {}),
|
2025-11-16 18:38:06 +01:00
|
|
|
|
file_path=path,
|
|
|
|
|
|
)
|
2025-11-08 17:29:25 +01:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(json.dumps({"path": path, "note_id": note_id, "error": f"chunk build failed: {type(e).__name__}: {e}"}))
|
|
|
|
|
|
continue
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Explizites Spiegeln: retriever_weight & chunk_profile auf JEDEN Chunk
|
|
|
|
|
|
rwf = float(rw) if isinstance(rw, (int, float)) else 1.0
|
|
|
|
|
|
cpv = fm.get("chunk_profile")
|
2025-11-16 18:16:29 +01:00
|
|
|
|
for i, pl in enumerate(chunk_pls):
|
|
|
|
|
|
if "index" not in pl:
|
|
|
|
|
|
pl["index"] = i
|
|
|
|
|
|
pl["ord"] = int(pl.get("index", i)) + 1
|
2025-11-16 18:38:06 +01:00
|
|
|
|
if "retriever_weight" not in pl:
|
|
|
|
|
|
pl["retriever_weight"] = rwf
|
2025-11-16 18:47:36 +01:00
|
|
|
|
if cpv is not None:
|
|
|
|
|
|
pl["chunk_profile"] = cpv
|
|
|
|
|
|
# entferne alte Aliasse
|
|
|
|
|
|
for alias in ("chunk_num", "Chunk_Number"):
|
|
|
|
|
|
pl.pop(alias, None)
|
2025-11-11 17:19:22 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Embeddings (optional)
|
2025-11-11 17:19:22 +01:00
|
|
|
|
vecs: List[List[float]] = [[0.0] * int(cfg.dim) for _ in chunk_pls]
|
|
|
|
|
|
if embed_texts and chunk_pls:
|
|
|
|
|
|
try:
|
|
|
|
|
|
texts_for_embed = [(pl.get("window") or pl.get("text") or "") for pl in chunk_pls]
|
|
|
|
|
|
vecs = embed_texts(texts_for_embed)
|
2025-11-08 17:29:25 +01:00
|
|
|
|
except Exception as e:
|
2025-11-11 17:19:22 +01:00
|
|
|
|
print(json.dumps({"path": path, "note_id": note_id, "warn": f"embed_texts failed, using zeros: {e}"}))
|
2025-11-08 15:25:18 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Artefakte vorhanden?
|
2025-11-11 17:19:22 +01:00
|
|
|
|
chunks_missing, edges_missing = artifacts_missing(client, cfg.prefix, note_id)
|
2025-11-10 12:20:09 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Edges
|
2025-11-11 17:19:22 +01:00
|
|
|
|
edges: List[Dict[str, Any]] = []
|
|
|
|
|
|
edges_failed = False
|
2025-11-16 18:47:36 +01:00
|
|
|
|
should_build_edges = (changed and True) or edges_missing # wenn Note geändert oder Kanten fehlen
|
2025-11-11 17:19:22 +01:00
|
|
|
|
if should_build_edges:
|
2025-11-10 12:20:09 +01:00
|
|
|
|
try:
|
2025-11-16 18:47:36 +01:00
|
|
|
|
note_refs = note_pl.get("references") or ""
|
2025-11-11 17:19:22 +01:00
|
|
|
|
edges = build_edges_for_note(note_id, chunk_pls, note_refs, include_note_scope_refs=note_scope_refs)
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
edges_failed = True
|
|
|
|
|
|
edges = []
|
|
|
|
|
|
print(json.dumps({"path": path, "note_id": note_id, "warn": f"build_edges_for_note failed, skipping edges: {type(e).__name__}: {e}"}))
|
2025-11-08 15:25:18 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Summary
|
|
|
|
|
|
print(json.dumps({
|
2025-11-08 14:25:31 +01:00
|
|
|
|
"note_id": note_id,
|
2025-11-08 15:25:18 +01:00
|
|
|
|
"title": fm.get("title"),
|
2025-11-16 18:07:56 +01:00
|
|
|
|
"type": fm.get("type"),
|
|
|
|
|
|
"rw": rw,
|
2025-11-16 18:47:36 +01:00
|
|
|
|
"chunk_profile": fm.get("chunk_profile"),
|
2025-11-08 15:25:18 +01:00
|
|
|
|
"chunks": len(chunk_pls),
|
2025-11-08 14:25:31 +01:00
|
|
|
|
"edges": len(edges),
|
2025-11-11 17:19:22 +01:00
|
|
|
|
"changed": changed,
|
|
|
|
|
|
"chunks_missing": chunks_missing,
|
|
|
|
|
|
"edges_missing": edges_missing,
|
2025-11-16 18:47:36 +01:00
|
|
|
|
"decision": ("apply" if args.apply else "dry-run"),
|
2025-11-11 17:19:22 +01:00
|
|
|
|
"prefix": cfg.prefix,
|
2025-11-16 18:47:36 +01:00
|
|
|
|
"path": note_pl["path"]
|
|
|
|
|
|
}, ensure_ascii=False))
|
2025-11-08 15:25:18 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Writes
|
2025-11-08 15:25:18 +01:00
|
|
|
|
if not args.apply:
|
2025-11-08 14:25:31 +01:00
|
|
|
|
continue
|
2025-11-08 11:53:06 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Purge bei Änderungen
|
|
|
|
|
|
if args.purge_before_upsert and changed:
|
2025-11-08 15:25:18 +01:00
|
|
|
|
try:
|
|
|
|
|
|
purge_note_artifacts(client, cfg.prefix, note_id)
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
print(json.dumps({"path": path, "note_id": note_id, "warn": f"purge failed: {e}"}))
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Note
|
2025-11-11 17:19:22 +01:00
|
|
|
|
if changed:
|
2025-11-09 10:42:55 +01:00
|
|
|
|
notes_name, note_pts = points_for_note(cfg.prefix, note_pl, None, cfg.dim)
|
|
|
|
|
|
upsert_batch(client, notes_name, note_pts)
|
|
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Chunks (wenn geändert ODER vorher keine vorhanden)
|
2025-11-09 10:42:55 +01:00
|
|
|
|
if chunk_pls and (changed or chunks_missing):
|
2025-11-08 17:00:27 +01:00
|
|
|
|
chunks_name, chunk_pts = points_for_chunks(cfg.prefix, chunk_pls, vecs)
|
|
|
|
|
|
upsert_batch(client, chunks_name, chunk_pts)
|
2025-11-09 10:42:55 +01:00
|
|
|
|
|
2025-11-16 18:47:36 +01:00
|
|
|
|
# Edges (wenn geändert ODER vorher keine vorhanden)
|
2025-11-09 10:42:55 +01:00
|
|
|
|
if edges and (changed or edges_missing):
|
2025-11-08 17:00:27 +01:00
|
|
|
|
edges_name, edge_pts = points_for_edges(cfg.prefix, edges)
|
|
|
|
|
|
upsert_batch(client, edges_name, edge_pts)
|
2025-11-08 11:53:06 +01:00
|
|
|
|
|
2025-11-08 15:25:18 +01:00
|
|
|
|
print(f"Done. Processed notes: {processed}")
|
2025-11-08 11:53:06 +01:00
|
|
|
|
|
2025-09-09 19:47:16 +02:00
|
|
|
|
|
2025-09-01 17:37:39 +02:00
|
|
|
|
if __name__ == "__main__":
|
2025-11-08 18:06:33 +01:00
|
|
|
|
main()
|