base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. if isinstance(self.outputs, type(None)):
  125. logging.debug(
  126. f"The `output_key` of {self.__class__.__name__} is None, so would not inspect!"
  127. )
  128. data.update(output_item)
  129. else:
  130. for k, v in self.outputs.items():
  131. if k not in output_item:
  132. raise Exception(
  133. f"The value ({k}) is needed by {self.__class__.__name__}. But not found in Data ({output_item.keys()})!"
  134. )
  135. data.update({v: output_item[k]})
  136. output_list.append(data)
  137. return output_list
  138. else:
  139. assert isinstance(ori_data, dict)
  140. output_list = []
  141. for output_item in output:
  142. data = ori_data.copy() if self.keep_input else {}
  143. if isinstance(self.outputs, type(None)):
  144. logging.debug(
  145. f"The `output_key` of {self.__class__.__name__} is None, so would not inspect!"
  146. )
  147. data.update(output_item)
  148. else:
  149. for k, v in self.outputs.items():
  150. if k not in output_item:
  151. raise Exception(
  152. f"The value ({k}) is needed by {self.__class__.__name__}. But not found in Data ({output_item.keys()})!"
  153. )
  154. data.update({v: output_item[k]})
  155. output_list.append(data)
  156. return output_list
  157. else:
  158. assert isinstance(ori_data, dict) and isinstance(output, dict)
  159. data = ori_data.copy() if self.keep_input else {}
  160. if isinstance(self.outputs, type(None)):
  161. logging.debug(
  162. f"The `output_key` of {self.__class__.__name__} is None, so would not inspect!"
  163. )
  164. data.update(output)
  165. else:
  166. for k, v in self.outputs.items():
  167. if k not in output:
  168. raise Exception(
  169. f"The value of key ({k}) is needed add to Data. But not found in output of {self.__class__.__name__}: ({output.keys()})!"
  170. )
  171. data.update({v: output[k]})
  172. return [data]
  173. def set_inputs(self, inputs):
  174. assert isinstance(inputs, dict)
  175. input_keys = deepcopy(self.INPUT_KEYS)
  176. # e.g, input_keys is None or []
  177. if input_keys is None or (
  178. isinstance(input_keys, list) and len(input_keys) == 0
  179. ):
  180. self.inputs = {}
  181. if inputs:
  182. raise Exception
  183. return
  184. # e.g, input_keys is 'img'
  185. if not isinstance(input_keys, list):
  186. input_keys = [[input_keys]]
  187. # e.g, input_keys is ['img'] or [['img']]
  188. elif len(input_keys) > 0:
  189. # e.g, input_keys is ['img']
  190. if not isinstance(input_keys[0], list):
  191. input_keys = [input_keys]
  192. ck_pass = False
  193. for key_group in input_keys:
  194. for key in key_group:
  195. if key not in inputs:
  196. break
  197. # check pass
  198. else:
  199. ck_pass = True
  200. if ck_pass == True:
  201. break
  202. else:
  203. raise Exception(
  204. f"The input {input_keys} are needed by {self.__class__.__name__}. But only get: {list(inputs.keys())}"
  205. )
  206. self.inputs = inputs
  207. def set_outputs(self, outputs):
  208. assert isinstance(outputs, dict)
  209. output_keys = deepcopy(self.OUTPUT_KEYS)
  210. if not isinstance(output_keys, list):
  211. output_keys = [output_keys]
  212. for k in output_keys:
  213. if k not in outputs:
  214. logging.debug(
  215. f"The output ({k}) of {self.__class__.__name__} would be abandon!"
  216. )
  217. self.outputs = outputs
  218. @classmethod
  219. def get_input_keys(cls) -> list:
  220. return cls.input_keys
  221. @classmethod
  222. def get_output_keys(cls) -> list:
  223. return cls.output_keys
  224. @property
  225. def need_batch_input(self):
  226. return getattr(self, "ENABLE_BATCH", False)
  227. @property
  228. def keep_input(self):
  229. return getattr(self, "KEEP_INPUT", True)
  230. @property
  231. def name(self):
  232. return getattr(self, "NAME", self.__class__.__name__)
  233. class ComponentsEngine(object):
  234. def __init__(self, ops):
  235. self.ops = ops
  236. self.keys = list(ops.keys())
  237. def __call__(self, data, i=0):
  238. data_gen = self.ops[self.keys[i]](data)
  239. if i + 1 < len(self.ops):
  240. for data in data_gen:
  241. yield from self.__call__(data, i + 1)
  242. else:
  243. yield from data_gen