mindnet/app/services/edge_registry.py

116 lines
4.3 KiB
Python
Raw Normal View History

2025-12-18 11:50:52 +01:00
"""
FILE: app/services/edge_registry.py
2025-12-18 18:40:46 +01:00
DESCRIPTION: Single Source of Truth für Kanten-Typen.
2025-12-18 12:17:10 +01:00
WP-22 Teil B: Registry & Validation.
2025-12-18 18:40:46 +01:00
HARD-LOGGING: Nutzt print() und logger für maximale Sichtbarkeit beim Systemstart.
VERSION: 0.6.6 (Diagnostic Update)
2025-12-18 11:50:52 +01:00
"""
import re
import os
import json
import logging
from typing import Dict, Optional, Set
2025-12-18 13:56:45 +01:00
from app.config import get_settings
2025-12-18 11:50:52 +01:00
logger = logging.getLogger(__name__)
class EdgeRegistry:
_instance = None
2025-12-18 18:40:46 +01:00
def __new__(cls, *args, **kwargs):
2025-12-18 11:50:52 +01:00
if cls._instance is None:
cls._instance = super(EdgeRegistry, cls).__new__(cls)
cls._instance.initialized = False
return cls._instance
2025-12-18 12:17:10 +01:00
def __init__(self, vault_root: Optional[str] = None):
if self.initialized:
return
2025-12-18 18:40:46 +01:00
# Sofortige Ausgabe beim Start (erscheint in journalctl)
print("--- [DICT-INIT] EdgeRegistry startup sequence initiated ---")
2025-12-18 18:37:23 +01:00
2025-12-18 18:40:46 +01:00
# Pfad-Ermittlung
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_master")
2025-12-18 18:37:23 +01:00
2025-12-18 18:40:46 +01:00
# Absolute Pfad-Konstruktion
if env_vocab_path:
self.full_vocab_path = os.path.abspath(env_vocab_path)
2025-12-18 18:37:23 +01:00
else:
self.full_vocab_path = os.path.abspath(
2025-12-18 18:40:46 +01:00
os.path.join(env_vault_root, "01_User_Manual", "01_edge_vocabulary.md")
2025-12-18 18:37:23 +01:00
)
self.unknown_log_path = "data/logs/unknown_edges.jsonl"
2025-12-18 12:17:10 +01:00
self.canonical_map: Dict[str, str] = {}
2025-12-18 11:50:52 +01:00
self.valid_types: Set[str] = set()
2025-12-18 12:17:10 +01:00
2025-12-18 11:50:52 +01:00
self._load_vocabulary()
self.initialized = True
def _load_vocabulary(self):
2025-12-18 12:17:10 +01:00
"""Parst die Markdown-Tabelle im Vault."""
2025-12-18 18:40:46 +01:00
print(f"--- [DICT-CHECK] Attempting to load: {self.full_vocab_path}")
2025-12-18 18:37:23 +01:00
if not os.path.exists(self.full_vocab_path):
2025-12-18 18:40:46 +01:00
msg = f"!!! [DICT-ERROR] Edge Vocabulary NOT found at: {self.full_vocab_path} !!!"
print(msg)
logger.warning(msg)
2025-12-18 11:50:52 +01:00
return
pattern = re.compile(r"\|\s*\*\*([a-z_]+)\*\*\s*\|\s*([^|]+)\|")
try:
2025-12-18 18:37:23 +01:00
with open(self.full_vocab_path, "r", encoding="utf-8") as f:
count_types = 0
count_aliases = 0
2025-12-18 11:50:52 +01:00
for line in f:
match = pattern.search(line)
if match:
canonical = match.group(1).strip()
aliases_str = match.group(2).strip()
self.valid_types.add(canonical)
2025-12-18 12:17:10 +01:00
self.canonical_map[canonical] = canonical
2025-12-18 18:37:23 +01:00
count_types += 1
2025-12-18 11:50:52 +01:00
if aliases_str and "Kein Alias" not in aliases_str:
aliases = [a.strip() for a in aliases_str.split(",") if a.strip()]
for alias in aliases:
2025-12-18 13:15:58 +01:00
clean_alias = alias.replace("`", "").lower().strip()
2025-12-18 11:50:52 +01:00
self.canonical_map[clean_alias] = canonical
2025-12-18 18:37:23 +01:00
count_aliases += 1
2025-12-18 11:50:52 +01:00
2025-12-18 18:40:46 +01:00
success_msg = f"=== [DICT-SUCCESS] Loaded {count_types} Types and {count_aliases} Aliases ==="
print(success_msg)
logger.info(success_msg)
2025-12-18 11:50:52 +01:00
except Exception as e:
2025-12-18 18:40:46 +01:00
err_msg = f"!!! [DICT-FATAL] Failed to parse Vocabulary: {e} !!!"
print(err_msg)
logger.error(err_msg)
2025-12-18 11:50:52 +01:00
def resolve(self, edge_type: str) -> str:
2025-12-18 14:00:08 +01:00
"""Normalisiert Kanten-Typen via Registry oder loggt Unbekannte."""
2025-12-18 18:40:46 +01:00
if not edge_type: return "related_to"
2025-12-18 11:50:52 +01:00
clean_type = edge_type.lower().strip().replace(" ", "_")
if clean_type in self.canonical_map:
return self.canonical_map[clean_type]
self._log_unknown(clean_type)
2025-12-18 12:17:10 +01:00
return clean_type
2025-12-18 11:50:52 +01:00
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")
2025-12-18 18:40:46 +01:00
except Exception: pass
2025-12-18 11:50:52 +01:00
2025-12-18 14:00:08 +01:00
# Singleton Instanz
2025-12-18 11:50:52 +01:00
registry = EdgeRegistry()