AnP/Python/AnP/Managers/ModelsManager.py

58 lines
1.7 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Self, Any, Sequence, TypeVar
from inspect import isclass
from AnP.Interfaces.Application.AnPInterface import AnPInterface
from AnP.Abstracts.ModelAbstract import ModelAbstract
from AnP.Utils.Common import Common
from AnP.Utils.Checks import Check
T = TypeVar("T", bound = ModelAbstract)
class ModelsManager:
def __init__(self:Self, anp:AnPInterface) -> None:
self.anp:AnPInterface = anp
self.__models:dict[str, ModelAbstract] = {}
self.update()
def update(self:Self) -> None:
key:str
for key in ("default_models_files", "models_files", "default_models", "models"):
self.add(self.anp.settings.get(key), True)
def reset(self:Self) -> None:
self.__models = {}
self.update()
def get(self:Self, Type:type[T], keys:str|Sequence[str]) -> T|None:
key:str
for key in Common.get_keys(keys):
if key in self.__models and (
isinstance(self.__models[key], Type) or
(isclass(self.__models[key]) and issubclass(self.__models[key], Type))
):
return self.__models[key]
return None
def add(self:Self, inputs:Any|None, overwrite:bool = False) -> None:
subinputs:dict[str, ModelAbstract]
for subinputs in self.anp.files.load_json(inputs, True):
for key, model in subinputs.items():
if Check.is_mark_key(key) and model is None:
continue
if isclass(model) and issubclass(model, ModelAbstract) and (
overwrite or key not in self.__models
):
self.__models[key] = model