base.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import yaml
  15. import codecs
  16. from pathlib import Path
  17. from abc import abstractmethod
  18. from ...utils.subclass_register import AutoRegisterABCMetaClass
  19. from ..components.base import BaseComponent, ComponentsEngine
  20. from .official_models import official_models
  21. class BasePredictor(BaseComponent, metaclass=AutoRegisterABCMetaClass):
  22. __is_base = True
  23. INPUT_KEYS = "x"
  24. OUTPUT_KEYS = None
  25. KEEP_INPUT = False
  26. MODEL_FILE_PREFIX = "inference"
  27. def __init__(self, model, **kwargs):
  28. super().__init__()
  29. self.model_dir = self._check_model(model)
  30. self.kwargs = kwargs
  31. self.config = self._load_config()
  32. self.components = self._build_components()
  33. self.engine = ComponentsEngine(self.components)
  34. # alias predict() to the __call__()
  35. self.predict = self.__call__
  36. def _check_model(self, model):
  37. if Path(model).exists():
  38. return Path(model)
  39. elif model in official_models:
  40. return official_models[model]
  41. else:
  42. raise Exception(
  43. f"The model ({model}) is no exists! Please using directory of local model files or model name supported by PaddleX!"
  44. )
  45. def _load_config(self):
  46. config_path = self.model_dir / f"{self.MODEL_FILE_PREFIX}.yml"
  47. with codecs.open(config_path, "r", "utf-8") as file:
  48. dic = yaml.load(file, Loader=yaml.FullLoader)
  49. return dic
  50. def apply(self, x):
  51. """predict"""
  52. yield from self.engine(x)
  53. @abstractmethod
  54. def _build_components(self):
  55. raise NotImplementedError