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