mindnet/app/core/ingestion.py

379 lines
17 KiB
Python
Raw Normal View History

2025-12-10 21:41:43 +01:00
"""
2025-12-15 15:40:39 +01:00
FILE: app/core/ingestion.py
2025-12-18 14:30:24 +01:00
DESCRIPTION: Haupt-Ingestion-Logik. Transformiert Markdown in den Graphen (Notes, Chunks, Edges).
2025-12-23 15:20:14 +01:00
WP-20: Integration von Smart Edge Allocation via Hybrid LLM (Gemini/Gemma/OpenRouter).
2025-12-23 14:33:51 +01:00
WP-22: Integration von Content Lifecycle (Status Gate) und Edge Registry Validation.
WP-22: Kontextsensitive Kanten-Validierung mit Fundort-Reporting (Zeilennummern).
WP-22: Multi-Hash Refresh für konsistente Change Detection.
2025-12-23 21:44:49 +01:00
FIX: Robuste Verarbeitung von LLM-Antworten (Dict vs String) zur Vermeidung von Item-Assignment-Errors.
VERSION: 2.11.5
2025-12-15 15:40:39 +01:00
STATUS: Active
2025-12-23 14:33:51 +01:00
DEPENDENCIES: app.core.parser, app.core.note_payload, app.core.chunker, app.services.llm_service, app.services.edge_registry
EXTERNAL_CONFIG: config/types.yaml, config/prompts.yaml
2025-12-10 21:41:43 +01:00
"""
import os
2025-12-23 14:33:51 +01:00
import json
2025-12-11 10:23:23 +01:00
import logging
2025-12-12 17:53:31 +01:00
import asyncio
import time
2025-12-11 10:23:23 +01:00
from typing import Dict, List, Optional, Tuple, Any
2025-12-10 21:41:43 +01:00
2025-12-11 10:23:23 +01:00
# Core Module Imports
2025-12-10 21:41:43 +01:00
from app.core.parser import (
read_markdown,
normalize_frontmatter,
validate_required_frontmatter,
2025-12-23 18:51:12 +01:00
extract_edges_with_context,
2025-12-10 21:41:43 +01:00
)
from app.core.note_payload import make_note_payload
2025-12-12 17:53:31 +01:00
from app.core.chunker import assemble_chunks, get_chunk_config
2025-12-10 21:41:43 +01:00
from app.core.chunk_payload import make_chunk_payloads
2025-12-11 10:23:23 +01:00
2025-12-12 18:10:26 +01:00
# Fallback für Edges
2025-12-10 21:41:43 +01:00
try:
from app.core.derive_edges import build_edges_for_note
except ImportError:
2025-12-12 17:53:31 +01:00
def build_edges_for_note(*args, **kwargs): return []
2025-12-10 21:41:43 +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,
)
2025-12-11 10:23:23 +01:00
from app.services.embeddings_client import EmbeddingsClient
2025-12-18 11:50:52 +01:00
from app.services.edge_registry import registry as edge_registry
2025-12-23 18:51:12 +01:00
from app.services.llm_service import LLMService
2025-12-10 21:41:43 +01:00
2025-12-11 10:23:23 +01:00
logger = logging.getLogger(__name__)
2025-12-12 17:53:31 +01:00
# --- Helper ---
2025-12-10 21:41:43 +01:00
def load_type_registry(custom_path: Optional[str] = None) -> dict:
2025-12-18 14:30:24 +01:00
"""Lädt die types.yaml zur Steuerung der typ-spezifischen Ingestion."""
2025-12-10 21:41:43 +01:00
import yaml
2025-12-23 18:51:12 +01:00
from app.config import get_settings
settings = get_settings()
path = custom_path or settings.MINDNET_TYPES_FILE
2025-12-12 17:53:31 +01:00
if not os.path.exists(path): return {}
2025-12-10 21:41:43 +01:00
try:
2025-12-12 17:53:31 +01:00
with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {}
except Exception: return {}
2025-12-10 21:41:43 +01:00
def resolve_note_type(requested: Optional[str], reg: dict) -> str:
2025-12-18 14:30:24 +01:00
"""Bestimmt den finalen Notiz-Typ (Fallback auf 'concept')."""
2025-12-10 21:41:43 +01:00
types = reg.get("types", {})
2025-12-12 17:53:31 +01:00
if requested and requested in types: return requested
2025-12-11 10:23:23 +01:00
return "concept"
2025-12-10 21:41:43 +01:00
def effective_chunk_profile_name(fm: dict, note_type: str, reg: dict) -> str:
2025-12-23 18:51:12 +01:00
"""Ermittelt den Namen des zu nutzenden Chunk-Profils."""
override = fm.get("chunking_profile") or fm.get("chunk_profile")
2025-12-23 18:51:12 +01:00
if override and isinstance(override, str): return override
2025-12-12 18:10:26 +01:00
t_cfg = reg.get("types", {}).get(note_type, {})
if t_cfg:
cp = t_cfg.get("chunking_profile") or t_cfg.get("chunk_profile")
if cp: return cp
return reg.get("defaults", {}).get("chunking_profile", "sliding_standard")
2025-12-12 18:10:26 +01:00
def effective_retriever_weight(fm: dict, note_type: str, reg: dict) -> float:
2025-12-23 18:51:12 +01:00
"""Ermittelt das effektive retriever_weight für das Scoring."""
override = fm.get("retriever_weight")
if override is not None:
try: return float(override)
except: pass
2025-12-12 18:10:26 +01:00
t_cfg = reg.get("types", {}).get(note_type, {})
2025-12-23 18:51:12 +01:00
if t_cfg and "retriever_weight" in t_cfg: return float(t_cfg["retriever_weight"])
2025-12-12 18:10:26 +01:00
return float(reg.get("defaults", {}).get("retriever_weight", 1.0))
2025-12-10 21:41:43 +01:00
class IngestionService:
2025-12-11 12:23:06 +01:00
def __init__(self, collection_prefix: str = None):
2025-12-23 14:33:51 +01:00
from app.config import get_settings
2025-12-23 15:20:14 +01:00
self.settings = get_settings()
2025-12-11 12:23:06 +01:00
2025-12-23 14:33:51 +01:00
self.prefix = collection_prefix or self.settings.COLLECTION_PREFIX
2025-12-10 21:41:43 +01:00
self.cfg = QdrantConfig.from_env()
2025-12-11 12:23:06 +01:00
self.cfg.prefix = self.prefix
2025-12-10 21:41:43 +01:00
self.client = get_client(self.cfg)
2025-12-23 21:44:49 +01:00
self.dim = self.settings.VECTOR_SIZE
2025-12-23 15:20:14 +01:00
self.registry = load_type_registry()
2025-12-11 10:23:23 +01:00
self.embedder = EmbeddingsClient()
2025-12-23 18:51:12 +01:00
self.llm = LLMService()
2025-12-11 10:23:23 +01:00
2025-12-23 18:51:12 +01:00
self.active_hash_mode = self.settings.CHANGE_DETECTION_MODE
2025-12-11 12:23:06 +01:00
try:
ensure_collections(self.client, self.prefix, self.dim)
ensure_payload_indexes(self.client, self.prefix)
except Exception as e:
2025-12-12 17:53:31 +01:00
logger.warning(f"DB init warning: {e}")
2025-12-10 21:41:43 +01:00
def _get_chunk_config_by_profile(self, profile_name: str, note_type: str) -> Dict[str, Any]:
2025-12-23 21:44:49 +01:00
"""Holt die Chunker-Parameter für ein spezifisches Profil."""
2025-12-23 15:20:14 +01:00
profiles = self.registry.get("chunking_profiles", {})
if profile_name in profiles:
cfg = profiles[profile_name].copy()
if "overlap" in cfg and isinstance(cfg["overlap"], list):
cfg["overlap"] = tuple(cfg["overlap"])
return cfg
return get_chunk_config(note_type)
2025-12-23 14:33:51 +01:00
async def _perform_smart_edge_allocation(self, text: str, note_id: str) -> List[Dict]:
"""
WP-20: Nutzt den Hybrid LLM Service für die semantische Kanten-Extraktion.
2025-12-23 18:51:12 +01:00
QUOTEN-SCHUTZ: Bevorzugt OpenRouter (Gemma 2), um Gemini-Tageslimits zu schonen.
2025-12-23 14:33:51 +01:00
"""
2025-12-23 18:51:12 +01:00
provider = "openrouter" if self.settings.OPENROUTER_API_KEY else self.settings.MINDNET_LLM_PROVIDER
2025-12-23 21:44:49 +01:00
model = self.settings.GEMMA_MODEL
2025-12-23 15:55:06 +01:00
2025-12-23 18:51:12 +01:00
logger.info(f"🚀 [Ingestion] Turbo-Mode: Extracting edges for '{note_id}' using {model} on {provider}")
2025-12-23 14:33:51 +01:00
2025-12-23 21:44:49 +01:00
# WP-22: Hole valide Typen für das Prompt-Template
edge_registry.ensure_latest()
valid_types_str = ", ".join(sorted(list(edge_registry.valid_types)))
2025-12-23 15:55:06 +01:00
template = self.llm.get_prompt("edge_extraction", provider)
2025-12-23 14:33:51 +01:00
try:
2025-12-23 21:44:49 +01:00
# Befülle das Template (v2.5.0 erwartet valid_types)
prompt = template.format(
text=text[:6000],
note_id=note_id,
valid_types=valid_types_str
)
2025-12-23 14:33:51 +01:00
response_json = await self.llm.generate_raw_response(
prompt=prompt,
priority="background",
2025-12-23 15:20:14 +01:00
force_json=True,
2025-12-23 15:55:06 +01:00
provider=provider,
2025-12-23 15:20:14 +01:00
model_override=model
2025-12-23 14:33:51 +01:00
)
2025-12-23 21:44:49 +01:00
# Robustes Parsing (WP-20 Fix für 'str' object assignment error)
raw_data = json.loads(response_json)
processed_edges = []
# Das LLM liefert manchmal ein Dict mit einem Key statt einer Liste
if isinstance(raw_data, dict):
logger.debug(f"ℹ️ [Ingestion] LLM returned dict for {note_id}, attempting recovery.")
for key in ["edges", "links", "results", "kanten"]:
if key in raw_data and isinstance(raw_data[key], list):
raw_data = raw_data[key]
break
if not isinstance(raw_data, list):
logger.warning(f"⚠️ [Ingestion] LLM output for {note_id} is not a list: {type(raw_data)}")
return []
for item in raw_data:
# Fall 1: Element ist bereits ein Dict (Idealfall)
if isinstance(item, dict) and "to" in item:
item["provenance"] = "semantic_ai"
item["line"] = f"ai-{provider}"
processed_edges.append(item)
# Fall 2: Element ist ein String (z.B. "kind:target") -> Umwandlung
elif isinstance(item, str) and ":" in item:
parts = item.split(":", 1)
processed_edges.append({
"to": parts[1].strip(),
"kind": parts[0].strip(),
"provenance": "semantic_ai",
"line": f"ai-{provider}"
})
else:
logger.debug(f"⏩ [Ingestion] Skipping unparseable AI edge: {item}")
return processed_edges
2025-12-23 14:33:51 +01:00
except Exception as e:
2025-12-23 18:51:12 +01:00
logger.warning(f"⚠️ [Ingestion] Smart Edge Allocation failed for {note_id} on {provider}: {e}")
2025-12-23 14:33:51 +01:00
return []
2025-12-11 10:23:23 +01:00
async def process_file(
2025-12-10 21:41:43 +01:00
self,
file_path: str,
vault_root: str,
force_replace: bool = False,
apply: bool = False,
purge_before: bool = False,
note_scope_refs: bool = False,
hash_source: str = "parsed",
2025-12-12 18:10:26 +01:00
hash_normalize: str = "canonical"
2025-12-10 21:41:43 +01:00
) -> Dict[str, Any]:
2025-12-23 14:33:51 +01:00
"""Verarbeitet eine Markdown-Datei und schreibt sie in den Graphen."""
result = {"path": file_path, "status": "skipped", "changed": False, "error": None}
2025-12-10 21:41:43 +01:00
2025-12-12 18:10:26 +01:00
# 1. Parse & Frontmatter Validation
2025-12-10 21:41:43 +01:00
try:
parsed = read_markdown(file_path)
if not parsed: return {**result, "error": "Empty or unreadable file"}
2025-12-10 21:41:43 +01:00
fm = normalize_frontmatter(parsed.frontmatter)
validate_required_frontmatter(fm)
except Exception as e:
2025-12-11 12:23:06 +01:00
logger.error(f"Validation failed for {file_path}: {e}")
2025-12-10 21:41:43 +01:00
return {**result, "error": f"Validation failed: {str(e)}"}
2025-12-23 14:33:51 +01:00
# --- WP-22: Content Lifecycle Gate ---
2025-12-18 11:50:52 +01:00
status = fm.get("status", "draft").lower().strip()
if status in ["system", "template", "archive", "hidden"]:
return {**result, "status": "skipped", "reason": f"lifecycle_status_{status}"}
2025-12-18 14:30:24 +01:00
# 2. Type & Config Resolution
2025-12-23 15:20:14 +01:00
note_type = resolve_note_type(fm.get("type"), self.registry)
2025-12-10 21:41:43 +01:00
fm["type"] = note_type
2025-12-23 15:20:14 +01:00
effective_profile = effective_chunk_profile_name(fm, note_type, self.registry)
effective_weight = effective_retriever_weight(fm, note_type, self.registry)
fm["chunk_profile"] = effective_profile
fm["retriever_weight"] = effective_weight
2025-12-12 18:10:26 +01:00
2025-12-23 15:20:14 +01:00
# 3. Build Note Payload
2025-12-10 21:41:43 +01:00
try:
2025-12-23 14:33:51 +01:00
note_pl = make_note_payload(parsed, vault_root=vault_root, hash_normalize=hash_normalize, hash_source=hash_source, file_path=file_path)
if not note_pl.get("fulltext"): note_pl["fulltext"] = getattr(parsed, "body", "") or ""
note_pl["retriever_weight"] = effective_weight
note_pl["chunk_profile"] = effective_profile
2025-12-18 11:50:52 +01:00
note_pl["status"] = status
2025-12-10 21:41:43 +01:00
note_id = note_pl["note_id"]
except Exception as e:
return {**result, "error": f"Payload build failed: {str(e)}"}
2025-12-23 18:51:12 +01:00
# 4. Change Detection (WP-22 Multi-Hash)
2025-12-10 21:41:43 +01:00
old_payload = None
if not force_replace:
old_payload = self._fetch_note_payload(note_id)
has_old = old_payload is not None
check_key = f"{self.active_hash_mode}:{hash_source}:{hash_normalize}"
2025-12-23 14:33:51 +01:00
old_hashes = (old_payload or {}).get("hashes", {})
old_hash = old_hashes.get(check_key) if isinstance(old_hashes, dict) else None
new_hash = note_pl.get("hashes", {}).get(check_key)
2025-12-23 14:33:51 +01:00
2025-12-10 21:41:43 +01:00
hash_changed = (old_hash != new_hash)
chunks_missing, edges_missing = self._artifacts_missing(note_id)
should_write = force_replace or (not has_old) or hash_changed or chunks_missing or edges_missing
if not should_write:
return {**result, "status": "unchanged", "note_id": note_id}
if not apply:
return {**result, "status": "dry-run", "changed": True, "note_id": note_id}
2025-12-18 14:30:24 +01:00
# 5. Processing (Chunking, Embedding, Edge Generation)
2025-12-10 21:41:43 +01:00
try:
body_text = getattr(parsed, "body", "") or ""
2025-12-23 17:56:44 +01:00
2025-12-23 18:51:12 +01:00
# WP-22 STABILITY PATCH: Prüfen, ob ensure_latest existiert
2025-12-23 17:56:44 +01:00
if hasattr(edge_registry, "ensure_latest"):
edge_registry.ensure_latest()
2025-12-23 14:33:51 +01:00
chunk_config = self._get_chunk_config_by_profile(effective_profile, note_type)
2025-12-12 17:53:31 +01:00
chunks = await assemble_chunks(fm["id"], body_text, fm["type"], config=chunk_config)
2025-12-10 21:41:43 +01:00
chunk_pls = make_chunk_payloads(fm, note_pl["path"], chunks, note_text=body_text)
vecs = []
2025-12-11 10:23:23 +01:00
if chunk_pls:
2025-12-10 21:41:43 +01:00
texts = [c.get("window") or c.get("text") or "" for c in chunk_pls]
2025-12-23 14:33:51 +01:00
vecs = await self.embedder.embed_documents(texts)
2025-12-18 11:50:52 +01:00
2025-12-23 15:20:14 +01:00
# --- WP-22/WP-20: Kanten-Extraktion & Validierung ---
2025-12-18 11:50:52 +01:00
edges = []
2025-12-23 14:33:51 +01:00
context = {"file": file_path, "note_id": note_id}
2025-12-23 17:56:44 +01:00
# A. Explizite User-Kanten
2025-12-23 14:33:51 +01:00
explicit_edges = extract_edges_with_context(parsed)
for e in explicit_edges:
e["kind"] = edge_registry.resolve(edge_type=e["kind"], provenance="explicit", context={**context, "line": e.get("line")})
edges.append(e)
2025-12-23 18:51:12 +01:00
# B. WP-20: Smart AI Edges (Hybrid Turbo Acceleration)
2025-12-23 14:33:51 +01:00
ai_edges = await self._perform_smart_edge_allocation(body_text, note_id)
for e in ai_edges:
2025-12-23 21:44:49 +01:00
# Validierung gegen EdgeRegistry (Vermeidet 'Transition' etc.)
valid_kind = edge_registry.resolve(edge_type=e.get("kind"), provenance="semantic_ai", context={**context, "line": e.get("line")})
e["kind"] = valid_kind
2025-12-23 14:33:51 +01:00
edges.append(e)
2025-12-23 18:51:12 +01:00
# C. System-Kanten (Struktur)
2025-12-23 15:20:14 +01:00
try:
raw_system_edges = build_edges_for_note(note_id, chunk_pls, note_level_references=note_pl.get("references", []), include_note_scope_refs=note_scope_refs)
except TypeError:
raw_system_edges = build_edges_for_note(note_id, chunk_pls)
2025-12-23 14:33:51 +01:00
for e in raw_system_edges:
2025-12-23 15:20:14 +01:00
valid_kind = edge_registry.resolve(edge_type=e.get("kind", "belongs_to"), provenance="structure", context={**context, "line": "system"})
2025-12-23 17:56:44 +01:00
if valid_kind:
e["kind"] = valid_kind
edges.append(e)
2025-12-11 12:23:06 +01:00
2025-12-10 21:41:43 +01:00
except Exception as e:
2025-12-23 18:51:12 +01:00
logger.error(f"Processing failed for {file_path}: {e}", exc_info=True)
2025-12-10 21:41:43 +01:00
return {**result, "error": f"Processing failed: {str(e)}"}
2025-12-23 17:56:44 +01:00
# 6. Upsert
2025-12-11 12:23:06 +01:00
try:
2025-12-23 15:20:14 +01:00
if purge_before and has_old: self._purge_artifacts(note_id)
2025-12-10 21:41:43 +01:00
2025-12-11 12:23:06 +01:00
n_name, n_pts = points_for_note(self.prefix, note_pl, None, self.dim)
upsert_batch(self.client, n_name, n_pts)
2025-12-10 21:41:43 +01:00
2025-12-11 12:23:06 +01:00
if chunk_pls and vecs:
c_name, c_pts = points_for_chunks(self.prefix, chunk_pls, vecs)
upsert_batch(self.client, c_name, c_pts)
2025-12-12 17:53:31 +01:00
2025-12-11 12:23:06 +01:00
if edges:
e_name, e_pts = points_for_edges(self.prefix, edges)
upsert_batch(self.client, e_name, e_pts)
2025-12-10 21:41:43 +01:00
2025-12-23 15:20:14 +01:00
return {"path": file_path, "status": "success", "changed": True, "note_id": note_id, "chunks_count": len(chunk_pls), "edges_count": len(edges)}
2025-12-11 12:23:06 +01:00
except Exception as e:
2025-12-23 18:51:12 +01:00
logger.error(f"Upsert failed for {note_id}: {e}", exc_info=True)
2025-12-11 12:23:06 +01:00
return {**result, "error": f"DB Upsert failed: {e}"}
2025-12-10 21:41:43 +01:00
def _fetch_note_payload(self, note_id: str) -> Optional[dict]:
from qdrant_client.http import models as rest
col = f"{self.prefix}_notes"
2025-12-11 12:23:06 +01:00
try:
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
pts, _ = self.client.scroll(collection_name=col, scroll_filter=f, limit=1, with_payload=True)
return pts[0].payload if pts else None
except: return None
2025-12-10 21:41:43 +01:00
def _artifacts_missing(self, note_id: str) -> Tuple[bool, bool]:
from qdrant_client.http import models as rest
2025-12-11 12:23:06 +01:00
try:
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
2025-12-23 14:33:51 +01:00
c_pts, _ = self.client.scroll(collection_name=f"{self.prefix}_chunks", scroll_filter=f, limit=1)
e_pts, _ = self.client.scroll(collection_name=f"{self.prefix}_edges", scroll_filter=f, limit=1)
2025-12-11 12:23:06 +01:00
return (not bool(c_pts)), (not bool(e_pts))
except: return True, True
2025-12-10 21:41:43 +01:00
def _purge_artifacts(self, note_id: str):
from qdrant_client.http import models as rest
f = rest.Filter(must=[rest.FieldCondition(key="note_id", match=rest.MatchValue(value=note_id))])
selector = rest.FilterSelector(filter=f)
for suffix in ["chunks", "edges"]:
2025-12-23 15:20:14 +01:00
try: self.client.delete(collection_name=f"{self.prefix}_{suffix}", points_selector=selector)
2025-12-23 18:51:12 +01:00
except Exception: pass
async def create_from_text(self, markdown_content: str, filename: str, vault_root: str, folder: str = "00_Inbox") -> Dict[str, Any]:
"""Hilfsmethode zur Erstellung einer Note aus einem Textstream."""
target_dir = os.path.join(vault_root, folder)
os.makedirs(target_dir, exist_ok=True)
file_path = os.path.join(target_dir, filename)
try:
with open(file_path, "w", encoding="utf-8") as f:
f.write(markdown_content)
f.flush()
os.fsync(f.fileno())
await asyncio.sleep(0.1)
logger.info(f"Written file to {file_path}")
except Exception as e:
return {"status": "error", "error": f"Disk write failed: {str(e)}"}
return await self.process_file(file_path=file_path, vault_root=vault_root, apply=True, force_replace=True, purge_before=True)