pipeline.py 11 KB

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