pipeline.py 12 KB

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