94 lines
3.6 KiB
Python
94 lines
3.6 KiB
Python
"""
|
|
FILE: app/services/edge_registry.py
|
|
DESCRIPTION: Single Source of Truth für Kanten-Typen. Parst '01_User_Manual/01_edge_vocabulary.md'.
|
|
WP-22 Teil B: Registry & Validation.
|
|
Beachtet den dynamischen Vault-Root aus ENV oder Parameter.
|
|
"""
|
|
import re
|
|
import os
|
|
import json
|
|
import logging
|
|
from typing import Dict, Optional, Set
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class EdgeRegistry:
|
|
_instance = None
|
|
|
|
def __new__(cls, vault_root: Optional[str] = None):
|
|
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
|
|
|
|
# Priorität: 1. Parameter -> 2. ENV -> 3. Default
|
|
self.vault_root = vault_root or os.getenv("MINDNET_VAULT_ROOT", "./vault")
|
|
self.vocab_rel_path = os.path.join("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."""
|
|
full_path = os.path.abspath(os.path.join(self.vault_root, self.vocab_rel_path))
|
|
|
|
if not os.path.exists(full_path):
|
|
logger.warning(f"Edge Vocabulary NOT found at: {full_path}. Registry is empty.")
|
|
return
|
|
|
|
# Regex für Markdown Tabellen: | **canonical** | Aliases | ...
|
|
pattern = re.compile(r"\|\s*\*\*([a-z_]+)\*\*\s*\|\s*([^|]+)\|")
|
|
|
|
try:
|
|
with open(full_path, "r", encoding="utf-8") as f:
|
|
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)
|
|
self.canonical_map[canonical] = canonical
|
|
|
|
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:
|
|
clean_alias = alias.replace("`", "").lower().strip()
|
|
self.canonical_map[clean_alias] = canonical
|
|
|
|
logger.info(f"EdgeRegistry loaded from {full_path}: {len(self.valid_types)} types.")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to parse Edge Vocabulary at {full_path}: {e}")
|
|
|
|
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(" ", "_")
|
|
|
|
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):
|
|
"""Schreibt unbekannte Typen für Review in ein Log."""
|
|
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
|
|
|
|
# Singleton Instanz
|
|
registry = EdgeRegistry() |