basic_predictor.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. from abc import abstractmethod
  15. import inspect
  16. from ....utils.subclass_register import AutoRegisterABCMetaClass
  17. from ....utils import logging
  18. from ...components.base import BaseComponent, ComponentsEngine
  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. from .base_predictor import BasePredictor
  23. class BasicPredictor(
  24. BasePredictor,
  25. DeviceSetMixin,
  26. PPOptionSetMixin,
  27. BatchSizeSetMixin,
  28. metaclass=AutoRegisterABCMetaClass,
  29. ):
  30. __is_base = True
  31. def __init__(self, model_dir, config=None, device=None, pp_option=None):
  32. super().__init__(model_dir=model_dir, config=config)
  33. if not pp_option:
  34. pp_option = PaddlePredictorOption(model_name=self.model_name)
  35. if device:
  36. pp_option.device = device
  37. self._pp_option = pp_option
  38. self.components = {}
  39. self._build_components()
  40. self.engine = ComponentsEngine(self.components)
  41. logging.debug(f"{self.__class__.__name__}: {self.model_dir}")
  42. def apply(self, input):
  43. """predict"""
  44. yield from self._generate_res(self.engine(input))
  45. @generatorable_method
  46. def _generate_res(self, batch_data):
  47. return [{"result": self._pack_res(data)} for data in batch_data]
  48. def _add_component(self, cmps):
  49. if not isinstance(cmps, list):
  50. cmps = [cmps]
  51. for cmp in cmps:
  52. if not isinstance(cmp, (list, tuple)):
  53. key = cmp.name
  54. else:
  55. assert len(cmp) == 2
  56. key = cmp[0]
  57. cmp = cmp[1]
  58. assert isinstance(key, str)
  59. assert isinstance(cmp, BaseComponent)
  60. assert (
  61. key not in self.components
  62. ), f"The key ({key}) has been used: {self.components}!"
  63. self.components[key] = cmp
  64. def set_predictor(self, **kwargs):
  65. for k in kwargs:
  66. if self._has_setter(k):
  67. setattr(self, k, kwargs[k])
  68. else:
  69. raise Exception(
  70. f"The arg({k}) is not supported to specify in predict() func! Only supports: {self._get_settable_attributes()}"
  71. )
  72. def _has_setter(self, attr):
  73. prop = getattr(self.__class__, attr, None)
  74. return isinstance(prop, property) and prop.fset is not None
  75. @classmethod
  76. def _get_settable_attributes(cls):
  77. return [
  78. name
  79. for name, obj in inspect.getmembers(cls, lambda o: isinstance(o, property))
  80. if obj.fset is not None
  81. ]
  82. @abstractmethod
  83. def _build_components(self):
  84. raise NotImplementedError
  85. @abstractmethod
  86. def _pack_res(self, data):
  87. raise NotImplementedError