diff --git a/scripts/import_markdown.py b/scripts/import_markdown.py index e3804eb..c64e18a 100644 --- a/scripts/import_markdown.py +++ b/scripts/import_markdown.py @@ -1,247 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Script: scripts/import_markdown.py — Markdown → Qdrant (Notes, Chunks, Edges) -Version: 3.8.3 -Datum: 2025-11-08 - -Änderungen gegenüber 3.8.2 --------------------------- -- Ruft **ensure_collections nie direkt** auf, sondern ausschließlich über - `_ensure_collections_compat(client, cfg, dim)`. -- Payload-Index-Erzeugung ausschließlich via `_ensure_payload_indexes_compat(client, cfg)`. -- Keine Annahmen über Signaturen im Projektstand; alle Varianten sind abgefedert. -""" -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 - -from app.core.parser import ( - read_markdown, - normalize_frontmatter, - validate_required_frontmatter, -) -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 -try: - from app.core.derive_edges import build_edges_for_note -except Exception: # pragma: no cover - from app.core.edges import build_edges_for_note # type: ignore - -# Qdrant-Basics -from app.core.qdrant import ( - QdrantConfig, - get_client, - ensure_collections, # nur für Wrapper, unten niemals direkt aufrufen! -) - -# Abwärtskompatibler Import für Payload-Index-Erzeugung -try: - from app.core.qdrant import ensure_payload_indexes as _ensure_payload_indexes -except Exception: - try: - from app.core.qdrant import ensure_payload_indices as _ensure_payload_indexes # älterer Funktionsname - except Exception: - def _ensure_payload_indexes(*_args, **_kwargs): - # No-Op: ältere Releases ohne dedizierte Index-Funktion - return None - -# Qdrant-Points Helfer (robust gegen ältere Namen/fehlende Module) -try: - from app.core.qdrant_points import ( - points_for_chunks as _points_for_chunks, - points_for_note as _points_for_note, - points_for_edges as _points_for_edges, - upsert_batch as _upsert_batch, - ) -except Exception: - # Lokale Fallback-Implementierungen (No-Break) - from qdrant_client.http import models as _rest - - def _collection_names(prefix: str): - return f"{prefix}_notes", f"{prefix}_chunks", f"{prefix}_edges" - - def _points_for_note(prefix: str, note_payload: dict, note_vec, dim: int): - notes_col, _, _ = _collection_names(prefix) - vec = note_vec if note_vec is not None else [0.0] * int(dim) - pid = note_payload.get("note_id") or note_payload.get("id") or "missing-note-id" - pt = _rest.PointStruct(id=str(pid), vector=vec, payload=note_payload) - return notes_col, [pt] - - def _points_for_chunks(prefix: str, chunk_payloads: list[dict], vectors: list[list[float]]): - _, chunks_col, _ = _collection_names(prefix) - pts = [] - for i, pl in enumerate(chunk_payloads): - pid = pl.get("chunk_id") or pl.get("id") or f"{pl.get('note_id','missing')}#{i+1}" - vec = vectors[i] if i < len(vectors) else None - if vec is None: - continue - pts.append(_rest.PointStruct(id=str(pid), vector=vec, payload=pl)) - return chunks_col, pts - - def _points_for_edges(prefix: str, edges: list[dict]): - _, _, edges_col = _collection_names(prefix) - pts = [] - for i, e in enumerate(edges): - # stabiler String-ID-Aufbau - src = e.get("source_id") or e.get("src_id") or "src" - dst = e.get("target_id") or e.get("dst_id") or "dst" - kind = e.get("kind") or e.get("edge_type") or "edge" - nid = e.get("note_id") or "note" - pid = f"{nid}:{kind}:{src}->{dst}:{i}" - pts.append(_rest.PointStruct(id=str(pid), vector=None, payload=e)) - return edges_col, pts - - def _upsert_batch(client, collection_name: str, points: list): - if not points: - return - client.upsert(collection_name=collection_name, points=points, wait=True) - -# NEU: Type-Registry (optional) -try: - from app.core.type_registry import load_type_registry, resolve_note_type, get_type_config, effective_chunk_profile -except Exception: - load_type_registry = None # type: ignore - resolve_note_type = None # type: ignore - get_type_config = None # type: ignore - effective_chunk_profile = None # type: ignore - -try: - from app.core.embed import embed_texts # optional -except Exception: - embed_texts = None - - -# --------------------------------------------------------------------- -# Helper -# --------------------------------------------------------------------- - -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 list_qdrant_note_ids(client, prefix: str) -> Set[str]: - notes_col, _, _ = collections(prefix) - out: Set[str] = set() - next_page = None - while True: - pts, next_page = client.scroll( - collection_name=notes_col, - with_payload=True, - with_vectors=False, - limit=256, - offset=next_page, - ) - if not pts: - break - for p in pts: - pl = p.payload or {} - nid = pl.get("note_id") - if isinstance(nid, str): - out.add(nid) - if next_page is None: - break - return out - - -def purge_note_artifacts(client, prefix: str, note_id: str) -> None: - _, 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: - client.delete( - collection_name=col, - points_selector=rest.FilterSelector(filter=filt), - wait=True - ) - except Exception as e: - print(json.dumps({"note_id": note_id, "warn": f"delete in {col} via filter failed: {e}"})) - - -def delete_note_everywhere(client, prefix: str, note_id: str) -> None: - 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: - client.delete( - collection_name=col, - points_selector=rest.FilterSelector(filter=filt), - wait=True - ) - except Exception as e: - print(json.dumps({"note_id": note_id, "warn": f"delete in {col} failed: {e}"})) - - -def _resolve_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 "full" - if v in ("frontmatter", "fm"): - return "frontmatter" - return "body" - - -def _env(key: str, default: str) -> str: - return (os.environ.get(key) or default).strip().lower() - - -def _resolve_dim(cfg) -> int: - # Try common attribute names on QdrantConfig - for attr in ("dim", "vector_dim", "dimension", "dimensions", "embedding_dim", "embed_dim", "vector_size", "size"): - try: - v = getattr(cfg, attr) - if isinstance(v, int) and v > 0: - return v - except Exception: - pass - # Try environment fallbacks - for key in ("MINDNET_DIM", "EMBED_DIM", "EMBEDDING_DIM", "QDRANT_VECTOR_DIM", "QDRANT_DIM", "VECTOR_DIM", "DIM"): - try: - v = int(os.environ.get(key, "").strip() or "0") - if v > 0: - return v - except Exception: - continue - # Conservative default: MiniLM 384d (im Projekt üblich) - return 384 - # ---- Compatibility wrappers (no direct calls to project-specific signatures) ---- def _ensure_collections_compat(client, cfg, dim): @@ -453,7 +209,15 @@ def main() -> None: 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) + new_hash_exact = (note_pl.get( + +# Deterministic UUIDv5 for stable Qdrant point IDs +import uuid as _uuid +_MN_NAMESPACE = _uuid.uuid5(_uuid.NAMESPACE_URL, "mindnet-default-namespace") +def _uuid5_deterministic(*parts: str) -> str: + base = ":".join(str(p) for p in parts if p is not None) + return str(_uuid.uuid5(_MN_NAMESPACE, base)) +"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)