pipeline.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 os, sys
  15. from typing import Any, Dict, Optional
  16. import numpy as np
  17. import cv2
  18. from ..base import BasePipeline
  19. from ..components import CropByBoxes
  20. from .result import SealRecognitionResult
  21. from ....utils import logging
  22. from ...utils.pp_option import PaddlePredictorOption
  23. from ...common.reader import ReadImage
  24. from ...common.batch_sampler import ImageBatchSampler
  25. from ..doc_preprocessor.result import DocPreprocessorResult
  26. # [TODO] 待更新models_new到models
  27. from ...models_new.object_detection.result import DetResult
  28. class SealRecognitionPipeline(BasePipeline):
  29. """Seal Recognition Pipeline"""
  30. entities = ["seal_recognition"]
  31. def __init__(
  32. self,
  33. config: Dict,
  34. device: str = None,
  35. pp_option: PaddlePredictorOption = None,
  36. use_hpip: bool = False,
  37. hpi_params: Optional[Dict[str, Any]] = None,
  38. ) -> None:
  39. """Initializes the seal recognition pipeline.
  40. Args:
  41. config (Dict): Configuration dictionary containing various settings.
  42. device (str, optional): Device to run the predictions on. Defaults to None.
  43. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  44. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  45. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  46. """
  47. super().__init__(
  48. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  49. )
  50. self.use_doc_preprocessor = False
  51. if "use_doc_preprocessor" in config:
  52. self.use_doc_preprocessor = config["use_doc_preprocessor"]
  53. if self.use_doc_preprocessor:
  54. doc_preprocessor_config = config["SubPipelines"]["DocPreprocessor"]
  55. self.doc_preprocessor_pipeline = self.create_pipeline(
  56. doc_preprocessor_config
  57. )
  58. self.use_layout_detection = True
  59. if "use_layout_detection" in config:
  60. self.use_layout_detection = config["use_layout_detection"]
  61. if self.use_layout_detection:
  62. layout_det_config = config["SubModules"]["LayoutDetection"]
  63. self.layout_det_model = self.create_model(layout_det_config)
  64. seal_ocr_config = config["SubPipelines"]["SealOCR"]
  65. self.seal_ocr_pipeline = self.create_pipeline(seal_ocr_config)
  66. self._crop_by_boxes = CropByBoxes()
  67. self.batch_sampler = ImageBatchSampler(batch_size=1)
  68. self.img_reader = ReadImage(format="BGR")
  69. def check_input_params_valid(
  70. self, input_params: Dict, layout_det_res: DetResult
  71. ) -> bool:
  72. """
  73. Check if the input parameters are valid based on the initialized models.
  74. Args:
  75. input_params (Dict): A dictionary containing input parameters.
  76. layout_det_res (DetResult): Layout detection result.
  77. Returns:
  78. bool: True if all required models are initialized according to input parameters, False otherwise.
  79. """
  80. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  81. logging.error(
  82. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  83. )
  84. return False
  85. if input_params["use_layout_detection"]:
  86. if layout_det_res is not None:
  87. logging.error(
  88. "The layout detection model has already been initialized, please set use_layout_detection=False"
  89. )
  90. return False
  91. if not self.use_layout_detection:
  92. logging.error(
  93. "Set use_layout_detection, but the models for layout detection are not initialized."
  94. )
  95. return False
  96. return True
  97. def predict_doc_preprocessor_res(
  98. self, image_array: np.ndarray, input_params: dict
  99. ) -> tuple[DocPreprocessorResult, np.ndarray]:
  100. """
  101. Preprocess the document image based on input parameters.
  102. Args:
  103. image_array (np.ndarray): The input image array.
  104. input_params (dict): Dictionary containing preprocessing parameters.
  105. Returns:
  106. tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
  107. result dictionary and the processed image array.
  108. """
  109. if input_params["use_doc_preprocessor"]:
  110. use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
  111. use_doc_unwarping = input_params["use_doc_unwarping"]
  112. doc_preprocessor_res = next(
  113. self.doc_preprocessor_pipeline(
  114. image_array,
  115. use_doc_orientation_classify=use_doc_orientation_classify,
  116. use_doc_unwarping=use_doc_unwarping,
  117. )
  118. )
  119. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  120. else:
  121. doc_preprocessor_res = {}
  122. doc_preprocessor_image = image_array
  123. return doc_preprocessor_res, doc_preprocessor_image
  124. def predict(
  125. self,
  126. input: str | list[str] | np.ndarray | list[np.ndarray],
  127. use_layout_detection: bool = True,
  128. use_doc_orientation_classify: bool = False,
  129. use_doc_unwarping: bool = False,
  130. layout_det_res: DetResult = None,
  131. **kwargs
  132. ) -> SealRecognitionResult:
  133. """
  134. This function predicts the seal recognition result for the given input.
  135. Args:
  136. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) of pdf(s) to be processed.
  137. use_layout_detection (bool): Whether to use layout detection.
  138. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  139. use_doc_unwarping (bool): Whether to use document unwarping.
  140. layout_det_res (DetResult): The layout detection result.
  141. It will be used if it is not None and use_layout_detection is False.
  142. **kwargs: Additional keyword arguments.
  143. Returns:
  144. SealRecognitionResult: The predicted seal recognition result.
  145. """
  146. input_params = {
  147. "use_layout_detection": use_layout_detection,
  148. "use_doc_preprocessor": self.use_doc_preprocessor,
  149. "use_doc_orientation_classify": use_doc_orientation_classify,
  150. "use_doc_unwarping": use_doc_unwarping,
  151. }
  152. if use_doc_orientation_classify or use_doc_unwarping:
  153. input_params["use_doc_preprocessor"] = True
  154. else:
  155. input_params["use_doc_preprocessor"] = False
  156. if not self.check_input_params_valid(input_params, layout_det_res):
  157. yield None
  158. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  159. image_array = self.img_reader(batch_data)[0]
  160. img_id += 1
  161. doc_preprocessor_res, doc_preprocessor_image = (
  162. self.predict_doc_preprocessor_res(image_array, input_params)
  163. )
  164. seal_res_list = []
  165. seal_region_id = 1
  166. if not input_params["use_layout_detection"] and layout_det_res is None:
  167. layout_det_res = {}
  168. seal_ocr_res = next(self.seal_ocr_pipeline(doc_preprocessor_image))
  169. seal_ocr_res["seal_region_id"] = seal_region_id
  170. seal_res_list.append(seal_ocr_res)
  171. seal_region_id += 1
  172. else:
  173. if input_params["use_layout_detection"]:
  174. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  175. for box_info in layout_det_res["boxes"]:
  176. if box_info["label"].lower() in ["seal"]:
  177. crop_img_info = self._crop_by_boxes(image_array, [box_info])
  178. crop_img_info = crop_img_info[0]
  179. seal_ocr_res = next(
  180. self.seal_ocr_pipeline(crop_img_info["img"])
  181. )
  182. seal_ocr_res["seal_region_id"] = seal_region_id
  183. seal_res_list.append(seal_ocr_res)
  184. seal_region_id += 1
  185. single_img_res = {
  186. "layout_det_res": layout_det_res,
  187. "doc_preprocessor_res": doc_preprocessor_res,
  188. "seal_res_list": seal_res_list,
  189. "input_params": input_params,
  190. "img_id": img_id,
  191. }
  192. yield SealRecognitionResult(single_img_res)