459 lines
17 KiB
Python
459 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
Script: scripts/import_markdown.py — Markdown → Qdrant (Notes, Chunks, Edges)
|
|
Version: 3.5.3
|
|
Datum: 2025-09-09
|
|
|
|
Neu in 3.5.3
|
|
------------
|
|
- **Fallback**, falls app.core.note_payload.make_note_payload(None) / non-dict zurückgibt:
|
|
Der Importer baut einen minimalen, korrekten Note-Payload selbst (inkl. Hash
|
|
gemäß --hash-mode/--hash-source/--hash-normalize) und läuft weiter.
|
|
- Detaillierte Debug-Ausgaben mit Typ/Preview, falls die Rückgabeform abweicht.
|
|
|
|
Kurzbeschreibung
|
|
----------------
|
|
- Liest Markdown-Dateien ein, erzeugt Notes/Chunks/Edges **idempotent**.
|
|
- Änderungserkennung (nur Inhalte, keine FS-Zeitstempel) konfigurierbar:
|
|
* --hash-mode: body | frontmatter | body+frontmatter | full (Alias)
|
|
- Env: MINDNET_HASH_MODE oder MINDNET_HASH_COMPARE (Body/Frontmatter/Full)
|
|
* --hash-normalize: canonical | none (Default: canonical)
|
|
* --hash-source: parsed (Default) | raw
|
|
* Optional: --compare-text (oder ENV MINDNET_COMPARE_TEXT=true)
|
|
* Signaturabgleich: Wechselt die Signatur (z. B. body→full, parsed→raw, canonical→none),
|
|
gilt die Note einmalig als geändert.
|
|
|
|
ENV / Qdrant
|
|
------------
|
|
- QDRANT_URL | QDRANT_HOST/QDRANT_PORT | QDRANT_API_KEY
|
|
- COLLECTION_PREFIX (Default: mindnet)
|
|
- VECTOR_DIM (Default: 384)
|
|
- MINDNET_NOTE_SCOPE_REFS: true|false (Default: false)
|
|
- MINDNET_COMPARE_TEXT: true|false (Default: false)
|
|
|
|
Aufruf-Beispiele
|
|
----------------
|
|
python3 -m scripts.import_markdown --vault ./vault
|
|
python3 -m scripts.import_markdown --vault ./vault --apply --hash-source raw --hash-normalize none
|
|
MINDNET_HASH_COMPARE=Full python3 -m scripts.import_markdown --vault ./vault --apply
|
|
python3 -m scripts.import_markdown --vault ./vault --apply --compare-text
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import difflib
|
|
import json
|
|
import os
|
|
import sys
|
|
from typing import Dict, List, Optional, Tuple, Any
|
|
from collections.abc import Mapping
|
|
|
|
from dotenv import load_dotenv
|
|
from qdrant_client.http import models as rest
|
|
|
|
from app.core.parser import (
|
|
read_markdown,
|
|
normalize_frontmatter,
|
|
validate_required_frontmatter,
|
|
extract_wikilinks,
|
|
FRONTMATTER_RE,
|
|
)
|
|
from app.core.note_payload import make_note_payload
|
|
from app.core.chunker import assemble_chunks
|
|
from app.core.chunk_payload import make_chunk_payloads
|
|
from app.core.edges import build_edges_for_note
|
|
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,
|
|
)
|
|
|
|
try:
|
|
from app.core.embed import embed_texts # optional
|
|
except Exception:
|
|
embed_texts = None
|
|
|
|
|
|
# ---------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------
|
|
|
|
def iter_md(root: str) -> List[str]:
|
|
out: List[str] = []
|
|
for dirpath, _, filenames in os.walk(root):
|
|
for fn in filenames:
|
|
if not fn.lower().endswith(".md"):
|
|
continue
|
|
p = os.path.join(dirpath, fn)
|
|
pn = p.replace("\\", "/")
|
|
if any(ex in pn for ex in ["/.obsidian/", "/_backup_frontmatter/", "/_imported/"]):
|
|
continue
|
|
out.append(p)
|
|
return sorted(out)
|
|
|
|
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))])
|
|
points, _ = client.scroll(
|
|
collection_name=notes_col,
|
|
scroll_filter=f,
|
|
with_payload=True,
|
|
with_vectors=False,
|
|
limit=1,
|
|
)
|
|
if not points:
|
|
return None
|
|
return points[0].payload or {}
|
|
|
|
def purge_note_artifacts(client, prefix: str, note_id: str) -> None:
|
|
_, chunks_col, edges_col = collections(prefix)
|
|
f_chunks = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
client.delete(collection_name=chunks_col, points_selector=f_chunks, wait=True)
|
|
f_edges = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
|
|
client.delete(collection_name=edges_col, points_selector=f_edges, wait=True)
|
|
|
|
def _normalize_rel_path(abs_path: str, vault_root: str) -> str:
|
|
try:
|
|
rel = os.path.relpath(abs_path, vault_root)
|
|
except Exception:
|
|
rel = abs_path
|
|
return rel.replace("\\", "/").lstrip("/")
|
|
|
|
def _resolve_hash_mode(val: Optional[str]) -> str:
|
|
v = (val or os.environ.get("MINDNET_HASH_MODE") or os.environ.get("MINDNET_HASH_COMPARE") or "body").strip().lower()
|
|
if v in ("full", "fulltext", "body+frontmatter", "bodyplusfrontmatter"):
|
|
return "body+frontmatter"
|
|
if v in ("frontmatter", "fm"):
|
|
return "frontmatter"
|
|
return "body"
|
|
|
|
def _normalize_body(body: str, mode: str) -> str:
|
|
if mode == "none":
|
|
return body if body is not None else ""
|
|
text = (body or "").replace("\r\n", "\n").replace("\r", "\n")
|
|
text = "\n".join(line.rstrip() for line in text.split("\n"))
|
|
return text
|
|
|
|
def _canon_fm(fm: Dict[str, Any]) -> str:
|
|
return json.dumps(fm or {}, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
|
|
|
|
def _read_raw_body(file_path: str) -> tuple[str, Dict[str, Any]]:
|
|
if not os.path.exists(file_path):
|
|
return "", {}
|
|
with open(file_path, "r", encoding="utf-8") as f:
|
|
raw = f.read()
|
|
m = FRONTMATTER_RE.match(raw)
|
|
fm = {}
|
|
if m:
|
|
import yaml
|
|
try:
|
|
fm = yaml.safe_load(m.group(1)) or {}
|
|
except Exception:
|
|
fm = {}
|
|
body = raw[m.end():]
|
|
else:
|
|
body = raw
|
|
return body, fm
|
|
|
|
def _fallback_note_payload(parsed: Any, vault_root: str, *, hash_mode: Optional[str], hash_normalize: Optional[str],
|
|
hash_source: Optional[str], file_path: str) -> Dict[str, Any]:
|
|
"""Baut einen minimalen Note-Payload, falls make_note_payload None liefert."""
|
|
fm = normalize_frontmatter(parsed.frontmatter)
|
|
path = getattr(parsed, "path", file_path)
|
|
rel_path = _normalize_rel_path(path, vault_root)
|
|
src = (hash_source or os.environ.get("MINDNET_HASH_SOURCE", "parsed")).strip().lower()
|
|
norm = (hash_normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical")).strip().lower()
|
|
mode = _resolve_hash_mode(hash_mode)
|
|
|
|
if src == "raw":
|
|
body_raw, fm_raw = _read_raw_body(file_path)
|
|
# Roh-FM ergänzen (nicht überschreiben)
|
|
if fm_raw:
|
|
merged = dict(fm)
|
|
for k, v in fm_raw.items():
|
|
merged.setdefault(k, v)
|
|
fm = merged
|
|
body_for_hash = body_raw
|
|
else:
|
|
body_for_hash = getattr(parsed, "body", "") or ""
|
|
|
|
body_n = _normalize_body(body_for_hash, norm)
|
|
fm_s = _canon_fm(fm)
|
|
|
|
import hashlib
|
|
def h(s: str) -> str:
|
|
x = hashlib.sha256()
|
|
x.update(s.encode("utf-8"))
|
|
return x.hexdigest()
|
|
|
|
if mode == "frontmatter":
|
|
primary_hash = h(fm_s)
|
|
elif mode == "body+frontmatter":
|
|
primary_hash = h(body_n + "\n--FM--\n" + fm_s)
|
|
else:
|
|
primary_hash = h(body_n)
|
|
|
|
sig = f"{'full' if mode=='body+frontmatter' else mode}:{src}:{norm}:{primary_hash}"
|
|
|
|
refs = extract_wikilinks(getattr(parsed, "body", "") or "")
|
|
|
|
return {
|
|
"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"),
|
|
"hash_fulltext": primary_hash,
|
|
"hash_signature": sig,
|
|
"fulltext": getattr(parsed, "body", "") or "",
|
|
"references": list(dict.fromkeys(refs)),
|
|
}
|
|
|
|
def _coerce_to_dict(obj: Any) -> Optional[Dict[str, Any]]:
|
|
if obj is None:
|
|
return None
|
|
if isinstance(obj, dict):
|
|
return obj
|
|
if isinstance(obj, Mapping):
|
|
try:
|
|
return dict(obj)
|
|
except Exception:
|
|
pass
|
|
if isinstance(obj, (list, tuple)):
|
|
for it in obj:
|
|
d = _coerce_to_dict(it)
|
|
if isinstance(d, dict):
|
|
return d
|
|
return None
|
|
md = getattr(obj, "model_dump", None)
|
|
if callable(md):
|
|
try: return md()
|
|
except Exception: pass
|
|
dd = getattr(obj, "dict", None)
|
|
if callable(dd):
|
|
try: return dd()
|
|
except Exception: pass
|
|
dct = getattr(obj, "__dict__", None)
|
|
if isinstance(dct, dict):
|
|
return dict(dct)
|
|
return None
|
|
|
|
|
|
# ---------------------------------------------------------------------
|
|
# Main
|
|
# ---------------------------------------------------------------------
|
|
|
|
def main() -> None:
|
|
load_dotenv()
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--vault", required=True, help="Pfad zum Obsidian-Vault (Root-Ordner)")
|
|
ap.add_argument("--apply", action="store_true", help="Schreibt in Qdrant; ohne Flag nur Dry-Run")
|
|
ap.add_argument("--purge-before-upsert", action="store_true",
|
|
help="Vor Upsert Chunks & Edges der GEÄNDERTEN Note löschen")
|
|
ap.add_argument("--note-id", help="Nur eine bestimmte Note-ID verarbeiten")
|
|
ap.add_argument("--embed-note", action="store_true", help="Optional: Note-Volltext einbetten")
|
|
ap.add_argument("--force-replace", action="store_true",
|
|
help="Änderungserkennung ignorieren und immer upserten (+ optional Purge)")
|
|
ap.add_argument("--hash-mode", choices=["body", "frontmatter", "body+frontmatter", "full"], default=None)
|
|
ap.add_argument("--hash-normalize", choices=["canonical", "none"], default=None)
|
|
ap.add_argument("--hash-source", choices=["parsed", "raw"], default=None)
|
|
ap.add_argument("--note-scope-refs", action="store_true")
|
|
ap.add_argument("--debug-hash-diff", action="store_true")
|
|
ap.add_argument("--compare-text", action="store_true")
|
|
args = ap.parse_args()
|
|
|
|
note_scope_refs_env = (os.environ.get("MINDNET_NOTE_SCOPE_REFS", "false").strip().lower() == "true")
|
|
note_scope_refs = args.note_scope_refs or note_scope_refs_env
|
|
compare_text = args.compare_text or (os.environ.get("MINDNET_COMPARE_TEXT", "false").strip().lower() == "true")
|
|
|
|
cfg = QdrantConfig.from_env()
|
|
client = get_client(cfg)
|
|
ensure_collections(client, cfg.prefix, cfg.dim)
|
|
ensure_payload_indexes(client, cfg.prefix)
|
|
|
|
root = os.path.abspath(args.vault)
|
|
files = iter_md(root)
|
|
if not files:
|
|
print("Keine Markdown-Dateien gefunden.", file=sys.stderr)
|
|
sys.exit(2)
|
|
|
|
processed = 0
|
|
for path in files:
|
|
# ------------- Parsing -------------
|
|
try:
|
|
parsed = read_markdown(path)
|
|
except Exception as e:
|
|
print(json.dumps({"path": path, "error": f"read_markdown failed: {e}"}))
|
|
continue
|
|
if parsed is None:
|
|
print(json.dumps({"path": path, "error": "read_markdown returned None"}))
|
|
continue
|
|
|
|
try:
|
|
fm = normalize_frontmatter(parsed.frontmatter)
|
|
validate_required_frontmatter(fm)
|
|
except Exception as e:
|
|
print(json.dumps({"path": path, "error": f"Frontmatter invalid: {e}"}))
|
|
continue
|
|
|
|
if args.note_id and fm.get("id") != args.note_id:
|
|
continue
|
|
|
|
processed += 1
|
|
|
|
# ------------- Note-Payload -------------
|
|
try:
|
|
note_pl_raw = make_note_payload(
|
|
parsed,
|
|
vault_root=root,
|
|
hash_mode=args.hash_mode,
|
|
hash_normalize=args.hash_normalize,
|
|
hash_source=args.hash_source,
|
|
file_path=path,
|
|
)
|
|
except Exception as e:
|
|
print(json.dumps({"path": path, "note_id": fm.get("id"), "error": f"make_note_payload failed: {e}"}))
|
|
note_pl_raw = None
|
|
|
|
note_pl = _coerce_to_dict(note_pl_raw)
|
|
if not isinstance(note_pl, dict):
|
|
# Fallback: baue minimalen Payload
|
|
note_pl = _fallback_note_payload(
|
|
parsed,
|
|
root,
|
|
hash_mode=args.hash_mode,
|
|
hash_normalize=args.hash_normalize,
|
|
hash_source=args.hash_source,
|
|
file_path=path,
|
|
)
|
|
print(json.dumps({
|
|
"path": path,
|
|
"note_id": fm.get("id"),
|
|
"warn": "make_note_payload returned non-dict; used fallback",
|
|
"returned_type": type(note_pl_raw).__name__ if note_pl_raw is not None else "NoneType"
|
|
}))
|
|
|
|
# fulltext + path Sicherheit
|
|
if not note_pl.get("fulltext"):
|
|
note_pl["fulltext"] = getattr(parsed, "body", "") or ""
|
|
if note_pl.get("path"):
|
|
note_pl["path"] = _normalize_rel_path(
|
|
os.path.join(root, note_pl["path"]) if not os.path.isabs(note_pl["path"]) else note_pl["path"], root
|
|
)
|
|
else:
|
|
p_path = getattr(parsed, "path", None) or path
|
|
note_pl["path"] = _normalize_rel_path(p_path, root)
|
|
|
|
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 (even in fallback)"}))
|
|
continue
|
|
|
|
# ------------- Change-Detection -------------
|
|
old_payload = None if args.force_replace else fetch_existing_note_payload(client, cfg.prefix, note_id)
|
|
old_hash = None if not old_payload else old_payload.get("hash_fulltext")
|
|
old_sig = (old_payload or {}).get("hash_signature")
|
|
new_hash = note_pl.get("hash_fulltext")
|
|
new_sig = note_pl.get("hash_signature")
|
|
|
|
sig_changed = bool(old_sig) and bool(new_sig) and (old_sig.split(":")[:3] != new_sig.split(":")[:3])
|
|
hash_changed = (old_hash != new_hash)
|
|
|
|
text_changed = False
|
|
if compare_text:
|
|
old_text = (old_payload or {}).get("fulltext") or ""
|
|
new_text = note_pl.get("fulltext") or ""
|
|
text_changed = (old_text != new_text)
|
|
|
|
changed = args.force_replace or sig_changed or hash_changed or text_changed
|
|
|
|
# ------------- Chunks / Embeddings / Edges -------------
|
|
try:
|
|
chunks = assemble_chunks(fm["id"], getattr(parsed, "body", "") or "", fm.get("type", "concept"))
|
|
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks)
|
|
except Exception as e:
|
|
print(json.dumps({"path": path, "note_id": note_id, "error": f"chunk build failed: {e}"}))
|
|
continue
|
|
|
|
if embed_texts:
|
|
try:
|
|
vecs = embed_texts([getattr(c, "text", "") for c in chunks]) # type: ignore[attr-defined]
|
|
except Exception as e:
|
|
print(json.dumps({"path": path, "note_id": note_id, "warn": f"embed_texts failed, using zeros: {e}"}))
|
|
vecs = [[0.0] * cfg.dim for _ in chunks]
|
|
else:
|
|
vecs = [[0.0] * cfg.dim for _ in chunks]
|
|
|
|
try:
|
|
note_refs = note_pl.get("references") or []
|
|
edges = build_edges_for_note(
|
|
note_id,
|
|
chunk_pls,
|
|
note_refs,
|
|
include_note_scope_refs=note_scope_refs,
|
|
)
|
|
except Exception as e:
|
|
print(json.dumps({"path": path, "note_id": note_id, "error": f"build_edges_for_note failed: {e}"}))
|
|
continue
|
|
|
|
# ------------- Summary -------------
|
|
summary = {
|
|
"note_id": note_id,
|
|
"title": fm.get("title"),
|
|
"chunks": len(chunk_pls),
|
|
"edges": len(edges),
|
|
"changed": changed,
|
|
"decision": ("apply" if args.apply and changed else
|
|
"apply-skip-unchanged" if args.apply and not changed else
|
|
"dry-run"),
|
|
"path": note_pl["path"],
|
|
"hash_mode": args.hash_mode or os.environ.get("MINDNET_HASH_MODE") or os.environ.get("MINDNET_HASH_COMPARE", "body"),
|
|
"hash_normalize": args.hash_normalize or os.environ.get("MINDNET_HASH_NORMALIZE", "canonical"),
|
|
"hash_source": args.hash_source or os.environ.get("MINDNET_HASH_SOURCE", "parsed"),
|
|
"hash_signature": note_pl.get("hash_signature"),
|
|
"sig_changed": sig_changed,
|
|
"hash_changed": hash_changed,
|
|
"text_changed": text_changed,
|
|
}
|
|
print(json.dumps(summary, ensure_ascii=False))
|
|
|
|
# ------------- Upserts -------------
|
|
if not args.apply:
|
|
continue
|
|
|
|
try:
|
|
if changed and args.purge_before_upsert:
|
|
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}"}))
|
|
|
|
try:
|
|
notes_name, note_pts = points_for_note(cfg.prefix, note_pl, None, cfg.dim)
|
|
upsert_batch(client, notes_name, note_pts)
|
|
chunks_name, chunk_pts = points_for_chunks(cfg.prefix, chunk_pls, vecs)
|
|
upsert_batch(client, chunks_name, chunk_pts)
|
|
edges_name, edge_pts = points_for_edges(cfg.prefix, edges)
|
|
upsert_batch(client, edges_name, edge_pts)
|
|
except Exception as e:
|
|
print(json.dumps({"path": path, "note_id": note_id, "error": f"upsert failed: {e}"}))
|
|
|
|
print(f"Done. Processed notes: {processed}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|