base.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 ...utils import logging
  20. from ..components.base import BaseComponent, ComponentsEngine
  21. from ..components.paddle_predictor.option import PaddlePredictorOption
  22. from ..utils.process_hook import generatorable_method
  23. class BasePredictor(BaseComponent, metaclass=AutoRegisterABCMetaClass):
  24. __is_base = True
  25. INPUT_KEYS = "x"
  26. DEAULT_INPUTS = {"x": "x"}
  27. OUTPUT_KEYS = "result"
  28. DEAULT_OUTPUTS = {"result": "result"}
  29. KEEP_INPUT = False
  30. MODEL_FILE_PREFIX = "inference"
  31. def __init__(self, model_dir, config=None, device=None, pp_option=None, **kwargs):
  32. super().__init__()
  33. self.model_dir = Path(model_dir)
  34. self.config = config if config else self.load_config(self.model_dir)
  35. self.kwargs = self._check_args(kwargs)
  36. self.pp_option = PaddlePredictorOption() if pp_option is None else pp_option
  37. if device is not None:
  38. self.pp_option.set_device(device)
  39. self.components = self._build_components()
  40. self.engine = ComponentsEngine(self.components)
  41. # alias predict() to the __call__()
  42. self.predict = self.__call__
  43. logging.debug(
  44. f"-------------------- {self.__class__.__name__} --------------------\nModel: {self.model_dir}\nEnv: {self.pp_option}"
  45. )
  46. @classmethod
  47. def load_config(cls, model_dir):
  48. config_path = model_dir / f"{cls.MODEL_FILE_PREFIX}.yml"
  49. with codecs.open(config_path, "r", "utf-8") as file:
  50. dic = yaml.load(file, Loader=yaml.FullLoader)
  51. return dic
  52. def apply(self, x):
  53. """predict"""
  54. yield from self._generate_res(self.engine(x))
  55. @generatorable_method
  56. def _generate_res(self, data):
  57. return self._pack_res(data)
  58. def _check_args(self, kwargs):
  59. return kwargs
  60. @abstractmethod
  61. def _build_components(self):
  62. raise NotImplementedError
  63. @abstractmethod
  64. def _pack_res(self, data):
  65. raise NotImplementedError