""" entity_registry.py 实体类型注册中心。 - extract_filtertext_v8.py 在生成实体时调用 register() 写入 - app.py 启动时调用 get_ontology_description() / get_node_types() 合并进配置 - 注册信息持久化到 entity_registry.json,跨进程保留 """ import json import os _REGISTRY_DIR = os.path.join(os.path.dirname(__file__), "registry") _REGISTRY_FILE = os.path.join(_REGISTRY_DIR, "entity_registry.json") os.makedirs(_REGISTRY_DIR, exist_ok=True) # 内存缓存,避免每次读文件 _cache: dict = {} def _load(): global _cache if _cache: return if os.path.exists(_REGISTRY_FILE): with open(_REGISTRY_FILE, encoding="utf-8") as f: _cache = json.load(f) else: _cache = {} def _save(): with open(_REGISTRY_FILE, "w", encoding="utf-8") as f: json.dump(_cache, f, ensure_ascii=False, indent=2) def register(entity_type: str, description: str = "", properties: list = None): """ 注册一个实体类型。已存在则跳过,不覆盖。 参数: entity_type: 实体类型名,如 "维修工作指导" description: 对该类型的描述(可为空) properties: 该类型的属性列表,如 ["名称", "内容", "knowledge_source"] """ _load() if entity_type in _cache: return # 已注册,不覆盖 _cache[entity_type] = { "description": description, "properties": properties or ["名称", "内容", "knowledge_source"] } _save() print(f" [registry] 注册新实体类型: 【{entity_type}】") def get_ontology_description() -> dict: """返回 {type: [description]} 格式,可直接合并进 Ontology_DESCRIPTION。""" _load() return {k: [v["description"]] for k, v in _cache.items()} def get_node_types() -> dict: """返回 {type: [properties]} 格式,可直接合并进 node_types。""" _load() return {k: v["properties"] for k, v in _cache.items()} def get_ontology_list() -> list: """返回所有已注册的实体类型名列表,可合并进 ontology。""" _load() return list(_cache.keys())