basic_predictor.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 .base_predictor import BasePredictor
  22. class BasicPredictor(
  23. BasePredictor,
  24. metaclass=AutoRegisterABCMetaClass,
  25. ):
  26. __is_base = True
  27. def __init__(self, model_dir, config=None, device=None, pp_option=None):
  28. super().__init__(model_dir=model_dir, config=config)
  29. if not pp_option:
  30. pp_option = PaddlePredictorOption(model_name=self.model_name)
  31. if device:
  32. pp_option.device = device
  33. self.pp_option = pp_option
  34. self.components = {}
  35. self._build_components()
  36. self.engine = ComponentsEngine(self.components)
  37. logging.debug(f"{self.__class__.__name__}: {self.model_dir}")
  38. def apply(self, input):
  39. """predict"""
  40. yield from self._generate_res(self.engine(input))
  41. @generatorable_method
  42. def _generate_res(self, batch_data):
  43. return [{"result": self._pack_res(data)} for data in batch_data]
  44. def _add_component(self, cmps):
  45. if not isinstance(cmps, list):
  46. cmps = [cmps]
  47. for cmp in cmps:
  48. if not isinstance(cmp, (list, tuple)):
  49. key = cmp.name
  50. else:
  51. assert len(cmp) == 2
  52. key = cmp[0]
  53. cmp = cmp[1]
  54. assert isinstance(key, str)
  55. assert isinstance(cmp, BaseComponent)
  56. assert (
  57. key not in self.components
  58. ), f"The key ({key}) has been used: {self.components}!"
  59. self.components[key] = cmp
  60. def set_predictor(self, batch_size=None, device=None, pp_option=None):
  61. if batch_size:
  62. self.components["ReadCmp"].batch_size = batch_size
  63. self.pp_option.batch_size = batch_size
  64. if device and device != self.pp_option.device:
  65. self.pp_option.device = device
  66. if pp_option and pp_option != self.pp_option:
  67. self.pp_option = pp_option
  68. def _has_setter(self, attr):
  69. prop = getattr(self.__class__, attr, None)
  70. return isinstance(prop, property) and prop.fset is not None
  71. @abstractmethod
  72. def _build_components(self):
  73. raise NotImplementedError
  74. @abstractmethod
  75. def _pack_res(self, data):
  76. raise NotImplementedError