""" FILE: app/services/edge_registry.py DESCRIPTION: Single Source of Truth für Kanten-Typen. FIX: Regex angepasst auf Format **`canonical`** (Bold + Backticks). VERSION: 0.6.10 (Regex Precision Update) """ import re import os import json import logging from typing import Dict, Optional, Set print(">>> MODULE_LOAD: edge_registry.py initialized <<<", flush=True) from app.config import get_settings logger = logging.getLogger(__name__) class EdgeRegistry: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super(EdgeRegistry, cls).__new__(cls) cls._instance.initialized = False return cls._instance def __init__(self, vault_root: Optional[str] = None): if self.initialized: return settings = get_settings() env_vocab_path = os.getenv("MINDNET_VOCAB_PATH") env_vault_root = os.getenv("MINDNET_VAULT_ROOT") or getattr(settings, "MINDNET_VAULT_ROOT", "./vault") if env_vocab_path: self.full_vocab_path = os.path.abspath(env_vocab_path) else: self.full_vocab_path = os.path.abspath( os.path.join(env_vault_root, "01_User_Manual", "01_edge_vocabulary.md") ) self.unknown_log_path = "data/logs/unknown_edges.jsonl" self.canonical_map: Dict[str, str] = {} self.valid_types: Set[str] = set() self._load_vocabulary() self.initialized = True def _load_vocabulary(self): """Parst die Markdown-Tabelle im Vault.""" print(f">>> CHECK: Loading Vocabulary from {self.full_vocab_path}", flush=True) if not os.path.exists(self.full_vocab_path): print(f"!!! [DICT-ERROR] File not found: {self.full_vocab_path} !!!", flush=True) return # WP-22 Precision Regex: # Sucht nach | **`typ`** | oder | **typ** | # Die Backticks `? sind jetzt optional enthalten. pattern = re.compile(r"\|\s*\*\*`?([a-zA-Z0-9_-]+)`?\*\*\s*\|\s*([^|]+)\|") try: with open(self.full_vocab_path, "r", encoding="utf-8") as f: c_types, c_aliases = 0, 0 for line in f: match = pattern.search(line) if match: canonical = match.group(1).strip().lower() aliases_str = match.group(2).strip() self.valid_types.add(canonical) self.canonical_map[canonical] = canonical c_types += 1 if aliases_str and "Kein Alias" not in aliases_str: # Aliase säubern (entfernt Backticks auch hier) aliases = [a.strip() for a in aliases_str.split(",") if a.strip()] for alias in aliases: clean_alias = alias.replace("`", "").lower().strip().replace(" ", "_") self.canonical_map[clean_alias] = canonical c_aliases += 1 if c_types == 0: print("!!! [DICT-WARN] Pattern mismatch! Ensure types are **`canonical`** or **canonical**. !!!", flush=True) else: print(f"=== [DICT-SUCCESS] Registered {c_types} Canonical Types and {c_aliases} Aliases ===", flush=True) except Exception as e: print(f"!!! [DICT-FATAL] Error reading file: {e} !!!", flush=True) def resolve(self, edge_type: str) -> str: """Normalisiert Kanten-Typen via Registry oder loggt Unbekannte.""" if not edge_type: return "related_to" clean_type = edge_type.lower().strip().replace(" ", "_").replace("-", "_") if clean_type in self.canonical_map: return self.canonical_map[clean_type] self._log_unknown(clean_type) return clean_type def _log_unknown(self, edge_type: str): try: os.makedirs(os.path.dirname(self.unknown_log_path), exist_ok=True) entry = {"unknown_type": edge_type, "status": "new"} with open(self.unknown_log_path, "a", encoding="utf-8") as f: f.write(json.dumps(entry) + "\n") except Exception: pass registry = EdgeRegistry()