From f7b1995b08576581de6d1f9a609b8c10fe99d363 Mon Sep 17 00:00:00 2001 From: Lars Date: Fri, 5 Sep 2025 07:33:05 +0200 Subject: [PATCH] scripts/import_markdown.py aktualisiert --- scripts/import_markdown.py | 105 ++++++++++++++++++++++--------------- 1 file changed, 63 insertions(+), 42 deletions(-) diff --git a/scripts/import_markdown.py b/scripts/import_markdown.py index c6435b9..981ab16 100644 --- a/scripts/import_markdown.py +++ b/scripts/import_markdown.py @@ -1,17 +1,41 @@ #!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Name: scripts/import_markdown.py +Version: v2.1.1 (2025-09-05) +Kurzbeschreibung: + Importiert Obsidian-Markdown-Notes in Qdrant (Notes/Chunks/Edges). + Leitet Wikilink-Edges (references/backlink/references_at) direkt beim Import + aus Volltext + echten Chunk-Texten ab. Keine Abhängigkeit zu edges.py (Legacy). + +Aufruf (aus Projekt-Root, im venv): + python3 -m scripts.import_markdown --vault ./vault [--apply] [--note-id NOTE_ID] [--embed-note] + +Parameter: + --vault Pfad zum Vault (z. B. ./vault) + --apply Führt Upserts in Qdrant aus (ohne Flag = Dry-Run mit JSON-Summaries) + --note-id Bearbeite nur eine konkrete Note-ID + --embed-note Optional: Note-Vektor (Volltext) zusätzlich einbetten + +Umgebungsvariablen (optional): + QDRANT_URL, QDRANT_API_KEY, COLLECTION_PREFIX, VECTOR_DIM (Default 384) + +Exitcodes: + 0 = OK, 2 = keine Markdown-Dateien gefunden + +Wichtige Hinweise: + - Verwendet ausschließlich app.core.derive_edges für Wikilink-Kanten. + - Chunk-Texte werden an derive_wikilink_edges übergeben; nur so entstehen references_at. + - Edges-IDs sind deterministisch (UUIDv5 in qdrant_points), idempotent. + - Edges-Collection bleibt 1D-Dummy-Vektor (DOT), reine Payload-Nutzung. + +Changelog: + v2.1.1: Entfernt Abhängigkeit auf app.core.edges; direkte Nutzung von derive_wikilink_edges; + sichert Übergabe der Chunk-Texte → references_at werden erzeugt. + v2.1.0: Note-Index über gesamten Vault; erste Fassung mit direkter Edge-Ableitung. + v2.0.x: Import Notes/Chunks/Embeddings, Edges via Backfill (separat). +""" from __future__ import annotations -""" -WP-03 – STEP 1 -Ziel dieses Patches: Edges (references/backlink/references_at) entstehen direkt beim Import -auf Basis der **echten Chunks** und eines **Vorab-Note-Index**. Damit verschwinden -"dangling" references_at-Quellen aus dem Backfill-Ansatz. - -Ausführung (aus Projekt-Root, im venv): - (.venv) python3 -m scripts.import_markdown --vault ./vault --apply - (.venv) python3 -m scripts.validate_edges --prefix mindnet --details - -Abhängigkeiten: qdrant-client, python-dotenv -""" import argparse import os import glob @@ -21,7 +45,7 @@ from typing import List, Dict from dotenv import load_dotenv -# Core-Module +# Core-Module (gemäß Projektstruktur) from app.core.parser import ( read_markdown, normalize_frontmatter, @@ -39,14 +63,10 @@ from app.core.qdrant_points import ( points_for_edges, upsert_batch, ) -# Neue direkte Edge-Ableitung beim Import +# Nur Wikilink-Ableitung (keine Kollision mit edges.py): from app.core.derive_edges import build_note_index, derive_wikilink_edges -# ----------------------------------------------------------------------------- -# Utilities -# ----------------------------------------------------------------------------- - def iter_md(root: str, exclude=("/.obsidian/", "/_backup_frontmatter/", "/_imported/")) -> List[str]: files = [p for p in glob.glob(os.path.join(root, "**", "*.md"), recursive=True)] out: List[str] = [] @@ -71,10 +91,6 @@ def minimal_note_index_payload(abs_path: str, vault_root: str) -> Dict: } -# ----------------------------------------------------------------------------- -# Main -# ----------------------------------------------------------------------------- - def main(): load_dotenv() @@ -85,7 +101,7 @@ def main(): ap.add_argument("--embed-note", action="store_true", help="Auch Note-Volltext einbetten (optional)") args = ap.parse_args() - # Qdrant + # Qdrant-Konfiguration (+ Collections sicherstellen) cfg = QdrantConfig( url=os.getenv("QDRANT_URL", "http://127.0.0.1:6333"), api_key=os.getenv("QDRANT_API_KEY") or None, @@ -101,28 +117,23 @@ def main(): print("Keine Markdown-Dateien gefunden.", file=sys.stderr) sys.exit(2) - # ------------------------------------------------------------------ - # (1) Vorab-Lauf: Note-Index für robuste Zielauflösung - # ------------------------------------------------------------------ + # (1) Vorab-Lauf: Note-Index (robuste Auflösung via ID/Titel-Slug/File-Slug) index_payloads: List[Dict] = [] for path in files: try: pl = minimal_note_index_payload(path, root) if not pl.get("note_id"): - # ohne stabile ID lassen wir die Note komplett aus continue if args.note_id and pl["note_id"] != args.note_id: continue index_payloads.append(pl) except Exception: - # bewusst still: Einzeldefekte sollen den Gesamtimport nicht stoppen + # Einzeldefekte nicht fatal continue - note_index = build_note_index(index_payloads) # (by_id, by_slug, by_file_slug) + note_index = build_note_index(index_payloads) - # ------------------------------------------------------------------ - # (2) Hauptlauf: pro Note Chunks/Embeddings + Edges aus echten Chunks - # ------------------------------------------------------------------ + # (2) Hauptlauf: Import + direkte Wikilink-Edge-Ableitung total_notes = 0 for path in files: parsed = read_markdown(path) @@ -154,31 +165,41 @@ def main(): note_vec = embed_one(parsed.body) # Edges direkt aus realen Chunks + Note-Index - # Für derive_wikilink_edges darf der Note-Payload einen Volltext enthalten - note_pl_for_edges = dict(note_pl) - note_pl_for_edges.setdefault("fulltext", parsed.body) - edges = derive_wikilink_edges(note_pl_for_edges, chunk_pls, note_index) + # ACHTUNG: derive_wikilink_edges erwartet Chunks mit Text → wir bauen eine + # minimalistische Liste {"chunk_id","text"} in gleicher Reihenfolge. + note_pl_for_edges = { + "note_id": fm["id"], + "title": fm.get("title"), + "path": note_pl["path"], + "fulltext": parsed.body, + } + chunks_for_links = [] + for i, pl in enumerate(chunk_pls): + cid = pl.get("chunk_id") or pl.get("id") + txt = chunks[i].text if i < len(chunks) else "" + chunks_for_links.append({"chunk_id": cid, "text": txt}) - # Dry-Run-Log - summary = { + edges = derive_wikilink_edges(note_pl_for_edges, chunks_for_links, note_index) + + # Dry-Run-Summary + print(json.dumps({ "note_id": fm["id"], "title": fm["title"], "chunks": len(chunk_pls), "edges": len(edges), "path": note_pl["path"], - } - print(json.dumps(summary, ensure_ascii=False)) + }, ensure_ascii=False)) if args.apply: # Notes upsert (idempotent; UUIDv5) notes_col, note_pts = points_for_note(cfg.prefix, note_pl, note_vec, cfg.dim) upsert_batch(client, notes_col, note_pts) - # Chunks upsert (idempotent; chunk_id stabilisiert notfalls qdrant_points) + # Chunks upsert (idempotent) chunks_col, chunk_pts = points_for_chunks(cfg.prefix, chunk_pls, vectors) upsert_batch(client, chunks_col, chunk_pts) - # Edges upsert (idempotent; edge_id deterministisch aus kind/src/tgt/seq) + # Edges upsert (idempotent; deterministisches edge_id) edges_col, edge_pts = points_for_edges(cfg.prefix, edges) upsert_batch(client, edges_col, edge_pts)