base_predictor.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 ...components.base import BaseComponent
  19. from ...utils.pp_option import PaddlePredictorOption
  20. from ...utils.process_hook import generatorable_method
  21. from ..utils.predict_set import DeviceSetMixin, PPOptionSetMixin, BatchSizeSetMixin
  22. class BasePredictor(BaseComponent):
  23. KEEP_INPUT = False
  24. YIELD_BATCH = False
  25. INPUT_KEYS = "x"
  26. DEAULT_INPUTS = {"x": "x"}
  27. OUTPUT_KEYS = "result"
  28. DEAULT_OUTPUTS = {"result": "result"}
  29. MODEL_FILE_PREFIX = "inference"
  30. def __init__(self, model_dir, config=None):
  31. super().__init__()
  32. self.model_dir = Path(model_dir)
  33. self.config = config if config else self.load_config(self.model_dir)
  34. # alias predict() to the __call__()
  35. self.predict = self.__call__
  36. def __call__(self, input, **kwargs):
  37. self.set_predictor(**kwargs)
  38. for res in super().__call__(input):
  39. yield res["result"]
  40. @property
  41. def config_path(self):
  42. return self.get_config_path(self.model_dir)
  43. @property
  44. def model_name(self) -> str:
  45. return self.config["Global"]["model_name"]
  46. @abstractmethod
  47. def apply(self, x):
  48. raise NotImplementedError
  49. @abstractmethod
  50. def set_predictor(self):
  51. raise NotImplementedError
  52. @classmethod
  53. def get_config_path(cls, model_dir):
  54. return model_dir / f"{cls.MODEL_FILE_PREFIX}.yml"
  55. @classmethod
  56. def load_config(cls, model_dir):
  57. config_path = cls.get_config_path(model_dir)
  58. with codecs.open(config_path, "r", "utf-8") as file:
  59. dic = yaml.load(file, Loader=yaml.FullLoader)
  60. return dic