base.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 inspect
  15. from copy import deepcopy
  16. from abc import ABC
  17. from types import GeneratorType
  18. from ...utils import logging
  19. class BaseComponent(ABC):
  20. INPUT_KEYS = None
  21. OUTPUT_KEYS = None
  22. def __init__(self):
  23. self.inputs = self.DEAULT_INPUTS if hasattr(self, "DEAULT_INPUTS") else {}
  24. self.outputs = self.DEAULT_OUTPUTS if hasattr(self, "DEAULT_OUTPUTS") else {}
  25. def __call__(self, input_list):
  26. # use list type for batched data
  27. if not isinstance(input_list, list):
  28. input_list = [input_list]
  29. output_list = []
  30. for args, input_ in self._check_input(input_list):
  31. output = self.apply(**args)
  32. if not output:
  33. yield input_list
  34. # output may be a generator, when the apply() uses yield
  35. if isinstance(output, GeneratorType):
  36. # if output is a generator, use for-in to get every one batch output data and yield one by one
  37. for each_output in output:
  38. reassemble_data = self._check_output(each_output, input_)
  39. yield reassemble_data
  40. # if output is not a generator, process all data of that and yield, so use output_list to collect all reassemble_data
  41. else:
  42. reassemble_data = self._check_output(output, input_)
  43. output_list.extend(reassemble_data)
  44. # avoid yielding output_list when the output is a generator
  45. if len(output_list) > 0:
  46. yield output_list
  47. def _check_input(self, input_list):
  48. # check if the value of input data meets the requirements of apply(),
  49. # and reassemble the parameters of apply() from input_list
  50. def _check_type(input_):
  51. if not isinstance(input_, dict):
  52. if len(self.inputs) == 1:
  53. key = list(self.inputs.keys())[0]
  54. input_ = {key: input_}
  55. else:
  56. raise Exception(
  57. f"The input must be a dict or a list of dict, unless the input of the component only requires one argument, but the component({self.__class__.__name__}) requires {list(self.inputs.keys())}!"
  58. )
  59. return input_
  60. def _check_args_key(args):
  61. sig = inspect.signature(self.apply)
  62. for param in sig.parameters.values():
  63. if param.default == inspect.Parameter.empty and param.name not in args:
  64. raise Exception(
  65. f"The parameter ({param.name}) is needed by {self.__class__.__name__}, but {list(args.keys())} only found!"
  66. )
  67. if self.need_batch_input:
  68. args = {}
  69. for input_ in input_list:
  70. input_ = _check_type(input_)
  71. for k, v in self.inputs.items():
  72. if v not in input_:
  73. raise Exception(
  74. f"The value ({v}) is needed by {self.__class__.__name__}. But not found in Data ({input_.keys()})!"
  75. )
  76. if k not in args:
  77. args[k] = []
  78. args[k].append(input_.get(v))
  79. _check_args_key(args)
  80. reassemble_input = [(args, input_list)]
  81. else:
  82. reassemble_input = []
  83. for input_ in input_list:
  84. input_ = _check_type(input_)
  85. args = {}
  86. for k, v in self.inputs.items():
  87. if v not in input_:
  88. raise Exception(
  89. f"The value ({v}) is needed by {self.__class__.__name__}. But not found in Data ({input_.keys()})!"
  90. )
  91. args[k] = input_.get(v)
  92. _check_args_key(args)
  93. reassemble_input.append((args, input_))
  94. return reassemble_input
  95. def _check_output(self, output, ori_data):
  96. # check if the value of apply() output data meets the requirements of setting
  97. # when the output data is list type, reassemble each of that
  98. if isinstance(output, list):
  99. if self.need_batch_input:
  100. assert isinstance(ori_data, list) and len(ori_data) == len(output)
  101. output_list = []
  102. for ori_item, output_item in zip(ori_data, output):
  103. data = ori_item.copy() if self.keep_ori else {}
  104. for k, v in self.outputs.items():
  105. if k not in output_item:
  106. raise Exception(
  107. f"The value ({k}) is needed by {self.__class__.__name__}. But not found in Data ({output_item.keys()})!"
  108. )
  109. data.update({v: output_item[k]})
  110. output_list.append(data)
  111. return output_list
  112. else:
  113. assert isinstance(ori_data, dict)
  114. output_list = []
  115. for output_item in output:
  116. data = ori_data.copy() if self.keep_ori else {}
  117. for k, v in self.outputs.items():
  118. if k not in output_item:
  119. raise Exception(
  120. f"The value ({k}) is needed by {self.__class__.__name__}. But not found in Data ({output_item.keys()})!"
  121. )
  122. data.update({v: output_item[k]})
  123. output_list.append(data)
  124. return output_list
  125. else:
  126. assert isinstance(ori_data, dict) and isinstance(output, dict)
  127. data = ori_data.copy() if self.keep_ori else {}
  128. for k, v in self.outputs.items():
  129. if k not in output:
  130. raise Exception(
  131. f"The value of key ({k}) is needed add to Data. But not found in output of {self.__class__.__name__}: ({output.keys()})!"
  132. )
  133. data.update({v: output[k]})
  134. return [data]
  135. def set_inputs(self, inputs):
  136. assert isinstance(inputs, dict)
  137. input_keys = deepcopy(self.INPUT_KEYS)
  138. # e.g, input_keys is None or []
  139. if input_keys is None or (
  140. isinstance(input_keys, list) and len(input_keys) == 0
  141. ):
  142. self.inputs = {}
  143. if inputs:
  144. raise Exception
  145. return
  146. # e.g, input_keys is 'img'
  147. if not isinstance(input_keys, list):
  148. input_keys = [[input_keys]]
  149. # e.g, input_keys is ['img'] or [['img']]
  150. elif len(input_keys) > 0:
  151. # e.g, input_keys is ['img']
  152. if not isinstance(input_keys[0], list):
  153. input_keys = [input_keys]
  154. ck_pass = False
  155. for key_group in input_keys:
  156. for key in key_group:
  157. if key not in inputs:
  158. break
  159. # check pass
  160. else:
  161. ck_pass = True
  162. if ck_pass == True:
  163. break
  164. else:
  165. raise Exception(
  166. f"The input {input_keys} are needed by {self.__class__.__name__}. But only get: {list(inputs.keys())}"
  167. )
  168. self.inputs = inputs
  169. def set_outputs(self, outputs):
  170. assert isinstance(outputs, dict)
  171. output_keys = deepcopy(self.OUTPUT_KEYS)
  172. if not isinstance(output_keys, list):
  173. output_keys = [output_keys]
  174. for k in output_keys:
  175. if k not in outputs:
  176. logging.debug(
  177. f"The output ({k}) of {self.__class__.__name__} would be abandon!"
  178. )
  179. self.outputs = outputs
  180. @classmethod
  181. def get_input_keys(cls) -> list:
  182. return cls.input_keys
  183. @classmethod
  184. def get_output_keys(cls) -> list:
  185. return cls.output_keys
  186. @property
  187. def need_batch_input(self):
  188. return getattr(self, "ENABLE_BATCH", False)
  189. @property
  190. def keep_ori(self):
  191. return getattr(self, "KEEP_INPUT", True)
  192. class ComponentsEngine(object):
  193. def __init__(self, ops):
  194. self.ops = ops
  195. self.keys = list(ops.keys())
  196. def __call__(self, data, i=0):
  197. data_gen = self.ops[self.keys[i]](data)
  198. if i + 1 < len(self.ops):
  199. for data in data_gen:
  200. yield from self.__call__(data, i + 1)
  201. else:
  202. yield from data_gen