pipeline.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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, Union, Tuple, List
  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 ...utils.hpi import HPIConfig
  24. from ...common.reader import ReadImage
  25. from ...common.batch_sampler import ImageBatchSampler
  26. from ..doc_preprocessor.result import DocPreprocessorResult
  27. from ...models.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_config: Optional[Union[Dict[str, Any], HPIConfig]] = 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 the high-performance
  45. inference plugin (HPIP) by default. Defaults to False.
  46. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  47. The default high-performance inference configuration dictionary.
  48. Defaults to None.
  49. """
  50. super().__init__(
  51. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_config=hpi_config
  52. )
  53. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  54. if self.use_doc_preprocessor:
  55. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  56. "DocPreprocessor",
  57. {
  58. "pipeline_config_error": "config error for doc_preprocessor_pipeline!"
  59. },
  60. )
  61. self.doc_preprocessor_pipeline = self.create_pipeline(
  62. doc_preprocessor_config
  63. )
  64. self.use_layout_detection = config.get("use_layout_detection", True)
  65. if self.use_layout_detection:
  66. layout_det_config = config.get("SubModules", {}).get(
  67. "LayoutDetection",
  68. {"model_config_error": "config error for layout_det_model!"},
  69. )
  70. layout_kwargs = {}
  71. if (threshold := layout_det_config.get("threshold", None)) is not None:
  72. layout_kwargs["threshold"] = threshold
  73. if (layout_nms := layout_det_config.get("layout_nms", None)) is not None:
  74. layout_kwargs["layout_nms"] = layout_nms
  75. if (
  76. layout_unclip_ratio := layout_det_config.get(
  77. "layout_unclip_ratio", None
  78. )
  79. ) is not None:
  80. layout_kwargs["layout_unclip_ratio"] = layout_unclip_ratio
  81. if (
  82. layout_merge_bboxes_mode := layout_det_config.get(
  83. "layout_merge_bboxes_mode", None
  84. )
  85. ) is not None:
  86. layout_kwargs["layout_merge_bboxes_mode"] = layout_merge_bboxes_mode
  87. self.layout_det_model = self.create_model(
  88. layout_det_config, **layout_kwargs
  89. )
  90. seal_ocr_config = config.get("SubPipelines", {}).get(
  91. "SealOCR", {"pipeline_config_error": "config error for seal_ocr_pipeline!"}
  92. )
  93. self.seal_ocr_pipeline = self.create_pipeline(seal_ocr_config)
  94. self._crop_by_boxes = CropByBoxes()
  95. self.batch_sampler = ImageBatchSampler(batch_size=1)
  96. self.img_reader = ReadImage(format="BGR")
  97. def check_model_settings_valid(
  98. self, model_settings: Dict, layout_det_res: DetResult
  99. ) -> bool:
  100. """
  101. Check if the input parameters are valid based on the initialized models.
  102. Args:
  103. model_settings (Dict): A dictionary containing input parameters.
  104. layout_det_res (DetResult): Layout detection result.
  105. Returns:
  106. bool: True if all required models are initialized according to input parameters, False otherwise.
  107. """
  108. if model_settings["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  109. logging.error(
  110. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  111. )
  112. return False
  113. if model_settings["use_layout_detection"]:
  114. if layout_det_res is not None:
  115. logging.error(
  116. "The layout detection model has already been initialized, please set use_layout_detection=False"
  117. )
  118. return False
  119. if not self.use_layout_detection:
  120. logging.error(
  121. "Set use_layout_detection, but the models for layout detection are not initialized."
  122. )
  123. return False
  124. return True
  125. def get_model_settings(
  126. self,
  127. use_doc_orientation_classify: Optional[bool],
  128. use_doc_unwarping: Optional[bool],
  129. use_layout_detection: Optional[bool],
  130. ) -> dict:
  131. """
  132. Get the model settings based on the provided parameters or default values.
  133. Args:
  134. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  135. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  136. use_layout_detection (Optional[bool]): Whether to use layout detection.
  137. Returns:
  138. dict: A dictionary containing the model settings.
  139. """
  140. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  141. use_doc_preprocessor = self.use_doc_preprocessor
  142. else:
  143. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  144. use_doc_preprocessor = True
  145. else:
  146. use_doc_preprocessor = False
  147. if use_layout_detection is None:
  148. use_layout_detection = self.use_layout_detection
  149. return dict(
  150. use_doc_preprocessor=use_doc_preprocessor,
  151. use_layout_detection=use_layout_detection,
  152. )
  153. def predict(
  154. self,
  155. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  156. use_doc_orientation_classify: Optional[bool] = None,
  157. use_doc_unwarping: Optional[bool] = None,
  158. use_layout_detection: Optional[bool] = None,
  159. layout_det_res: Optional[DetResult] = None,
  160. layout_threshold: Optional[Union[float, dict]] = None,
  161. layout_nms: Optional[bool] = None,
  162. layout_unclip_ratio: Optional[Union[float, Tuple[float, float]]] = None,
  163. layout_merge_bboxes_mode: Optional[str] = None,
  164. seal_det_limit_side_len: Optional[int] = None,
  165. seal_det_limit_type: Optional[str] = None,
  166. seal_det_thresh: Optional[float] = None,
  167. seal_det_box_thresh: Optional[float] = None,
  168. seal_det_unclip_ratio: Optional[float] = None,
  169. seal_rec_score_thresh: Optional[float] = None,
  170. **kwargs,
  171. ) -> SealRecognitionResult:
  172. model_settings = self.get_model_settings(
  173. use_doc_orientation_classify, use_doc_unwarping, use_layout_detection
  174. )
  175. if not self.check_model_settings_valid(model_settings, layout_det_res):
  176. yield {"error": "the input params for model settings are invalid!"}
  177. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  178. image_array = self.img_reader(batch_data.instances)[0]
  179. if model_settings["use_doc_preprocessor"]:
  180. doc_preprocessor_res = next(
  181. self.doc_preprocessor_pipeline(
  182. image_array,
  183. use_doc_orientation_classify=use_doc_orientation_classify,
  184. use_doc_unwarping=use_doc_unwarping,
  185. )
  186. )
  187. else:
  188. doc_preprocessor_res = {"output_img": image_array}
  189. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  190. seal_res_list = []
  191. seal_region_id = 1
  192. if not model_settings["use_layout_detection"] and layout_det_res is None:
  193. layout_det_res = {}
  194. seal_ocr_res = next(
  195. self.seal_ocr_pipeline(
  196. doc_preprocessor_image,
  197. text_det_limit_side_len=seal_det_limit_side_len,
  198. text_det_limit_type=seal_det_limit_type,
  199. text_det_thresh=seal_det_thresh,
  200. text_det_box_thresh=seal_det_box_thresh,
  201. text_det_unclip_ratio=seal_det_unclip_ratio,
  202. text_rec_score_thresh=seal_rec_score_thresh,
  203. )
  204. )
  205. seal_ocr_res["seal_region_id"] = seal_region_id
  206. seal_res_list.append(seal_ocr_res)
  207. seal_region_id += 1
  208. else:
  209. if model_settings["use_layout_detection"]:
  210. layout_det_res = next(
  211. self.layout_det_model(
  212. doc_preprocessor_image,
  213. threshold=layout_threshold,
  214. layout_nms=layout_nms,
  215. layout_unclip_ratio=layout_unclip_ratio,
  216. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  217. )
  218. )
  219. for box_info in layout_det_res["boxes"]:
  220. if box_info["label"].lower() in ["seal"]:
  221. crop_img_info = self._crop_by_boxes(
  222. doc_preprocessor_image, [box_info]
  223. )
  224. crop_img_info = crop_img_info[0]
  225. seal_ocr_res = next(
  226. self.seal_ocr_pipeline(
  227. crop_img_info["img"],
  228. text_det_limit_side_len=seal_det_limit_side_len,
  229. text_det_limit_type=seal_det_limit_type,
  230. text_det_thresh=seal_det_thresh,
  231. text_det_box_thresh=seal_det_box_thresh,
  232. text_det_unclip_ratio=seal_det_unclip_ratio,
  233. text_rec_score_thresh=seal_rec_score_thresh,
  234. )
  235. )
  236. seal_ocr_res["seal_region_id"] = seal_region_id
  237. seal_res_list.append(seal_ocr_res)
  238. seal_region_id += 1
  239. single_img_res = {
  240. "input_path": batch_data.input_paths[0],
  241. "page_index": batch_data.page_indexes[0],
  242. "doc_preprocessor_res": doc_preprocessor_res,
  243. "layout_det_res": layout_det_res,
  244. "seal_res_list": seal_res_list,
  245. "model_settings": model_settings,
  246. }
  247. yield SealRecognitionResult(single_img_res)