base.py 9.6 KB

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