pipeline.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. from typing import Any, Dict, Optional
  15. import os, sys
  16. import numpy as np
  17. import cv2
  18. from ..base import BasePipeline
  19. from .utils import convert_points_to_boxes, get_sub_regions_ocr_res
  20. from .result import LayoutParsingResult
  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 ..ocr.result import OCRResult
  26. from ..doc_preprocessor.result import DocPreprocessorResult
  27. # [TODO] 待更新models_new到models
  28. from ...models_new.object_detection.result import DetResult
  29. class LayoutParsingPipeline(BasePipeline):
  30. """Layout Parsing Pipeline"""
  31. entities = ["layout_parsing"]
  32. def __init__(
  33. self,
  34. config: Dict,
  35. device: str = None,
  36. pp_option: PaddlePredictorOption = None,
  37. use_hpip: bool = False,
  38. hpi_params: Optional[Dict[str, Any]] = None,
  39. ) -> None:
  40. """Initializes the layout parsing pipeline.
  41. Args:
  42. config (Dict): Configuration dictionary containing various settings.
  43. device (str, optional): Device to run the predictions on. Defaults to None.
  44. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  45. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  46. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  47. """
  48. super().__init__(
  49. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  50. )
  51. self.inintial_predictor(config)
  52. self.batch_sampler = ImageBatchSampler(batch_size=1)
  53. self.img_reader = ReadImage(format="BGR")
  54. def set_used_models_flag(self, config: Dict) -> None:
  55. """
  56. Set the flags for which models to use based on the configuration.
  57. Args:
  58. config (Dict): A dictionary containing configuration settings.
  59. Returns:
  60. None
  61. """
  62. pipeline_name = config["pipeline_name"]
  63. self.pipeline_name = pipeline_name
  64. self.use_doc_preprocessor = False
  65. self.use_general_ocr = False
  66. self.use_seal_recognition = False
  67. self.use_table_recognition = False
  68. if "use_doc_preprocessor" in config:
  69. self.use_doc_preprocessor = config["use_doc_preprocessor"]
  70. if "use_general_ocr" in config:
  71. self.use_general_ocr = config["use_general_ocr"]
  72. if "use_seal_recognition" in config:
  73. self.use_seal_recognition = config["use_seal_recognition"]
  74. if "use_table_recognition" in config:
  75. self.use_table_recognition = config["use_table_recognition"]
  76. def inintial_predictor(self, config: Dict) -> None:
  77. """Initializes the predictor based on the provided configuration.
  78. Args:
  79. config (Dict): A dictionary containing the configuration for the predictor.
  80. Returns:
  81. None
  82. """
  83. self.set_used_models_flag(config)
  84. layout_det_config = config["SubModules"]["LayoutDetection"]
  85. self.layout_det_model = self.create_model(layout_det_config)
  86. if self.use_doc_preprocessor:
  87. doc_preprocessor_config = config["SubPipelines"]["DocPreprocessor"]
  88. self.doc_preprocessor_pipeline = self.create_pipeline(
  89. doc_preprocessor_config
  90. )
  91. if self.use_general_ocr or self.use_table_recognition:
  92. general_ocr_config = config["SubPipelines"]["GeneralOCR"]
  93. self.general_ocr_pipeline = self.create_pipeline(general_ocr_config)
  94. if self.use_seal_recognition:
  95. seal_recognition_config = config["SubPipelines"]["SealRecognition"]
  96. self.seal_recognition_pipeline = self.create_pipeline(
  97. seal_recognition_config
  98. )
  99. if self.use_table_recognition:
  100. table_recognition_config = config["SubPipelines"]["TableRecognition"]
  101. self.table_recognition_pipeline = self.create_pipeline(
  102. table_recognition_config
  103. )
  104. return
  105. def get_text_paragraphs_ocr_res(
  106. self, overall_ocr_res: OCRResult, layout_det_res: DetResult
  107. ) -> OCRResult:
  108. """
  109. Retrieves the OCR results for text paragraphs, excluding those of formulas, tables, and seals.
  110. Args:
  111. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  112. layout_det_res (DetResult): The detection result containing the layout information of the document.
  113. Returns:
  114. OCRResult: The OCR result for text paragraphs after excluding formulas, tables, and seals.
  115. """
  116. object_boxes = []
  117. for box_info in layout_det_res["boxes"]:
  118. if box_info["label"].lower() in ["formula", "table", "seal"]:
  119. object_boxes.append(box_info["coordinate"])
  120. object_boxes = np.array(object_boxes)
  121. return get_sub_regions_ocr_res(overall_ocr_res, object_boxes, flag_within=False)
  122. def check_input_params_valid(self, input_params: Dict) -> bool:
  123. """
  124. Check if the input parameters are valid based on the initialized models.
  125. Args:
  126. input_params (Dict): A dictionary containing input parameters.
  127. Returns:
  128. bool: True if all required models are initialized according to input parameters, False otherwise.
  129. """
  130. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  131. logging.error(
  132. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  133. )
  134. return False
  135. if input_params["use_general_ocr"] and not self.use_general_ocr:
  136. logging.error(
  137. "Set use_general_ocr, but the models for general OCR are not initialized."
  138. )
  139. return False
  140. if input_params["use_seal_recognition"] and not self.use_seal_recognition:
  141. logging.error(
  142. "Set use_seal_recognition, but the models for seal recognition are not initialized."
  143. )
  144. return False
  145. if input_params["use_table_recognition"] and not self.use_table_recognition:
  146. logging.error(
  147. "Set use_table_recognition, but the models for table recognition are not initialized."
  148. )
  149. return False
  150. return True
  151. def predict_doc_preprocessor_res(
  152. self, image_array: np.ndarray, input_params: dict
  153. ) -> tuple[DocPreprocessorResult, np.ndarray]:
  154. """
  155. Preprocess the document image based on input parameters.
  156. Args:
  157. image_array (np.ndarray): The input image array.
  158. input_params (dict): Dictionary containing preprocessing parameters.
  159. Returns:
  160. tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
  161. result dictionary and the processed image array.
  162. """
  163. if input_params["use_doc_preprocessor"]:
  164. use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
  165. use_doc_unwarping = input_params["use_doc_unwarping"]
  166. doc_preprocessor_res = next(
  167. self.doc_preprocessor_pipeline(
  168. image_array,
  169. use_doc_orientation_classify=use_doc_orientation_classify,
  170. use_doc_unwarping=use_doc_unwarping,
  171. )
  172. )
  173. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  174. else:
  175. doc_preprocessor_res = {}
  176. doc_preprocessor_image = image_array
  177. return doc_preprocessor_res, doc_preprocessor_image
  178. def predict_overall_ocr_res(self, image_array: np.ndarray) -> OCRResult:
  179. """
  180. Predict the overall OCR result for the given image array.
  181. Args:
  182. image_array (np.ndarray): The input image array to perform OCR on.
  183. Returns:
  184. OCRResult: The predicted OCR result with updated dt_boxes.
  185. """
  186. overall_ocr_res = next(self.general_ocr_pipeline(image_array))
  187. dt_boxes = convert_points_to_boxes(overall_ocr_res["dt_polys"])
  188. overall_ocr_res["dt_boxes"] = dt_boxes
  189. return overall_ocr_res
  190. def predict(
  191. self,
  192. input: str | list[str] | np.ndarray | list[np.ndarray],
  193. use_doc_orientation_classify: bool = False,
  194. use_doc_unwarping: bool = False,
  195. use_general_ocr: bool = True,
  196. use_seal_recognition: bool = True,
  197. use_table_recognition: bool = True,
  198. **kwargs
  199. ) -> LayoutParsingResult:
  200. """
  201. This function predicts the layout parsing result for the given input.
  202. Args:
  203. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or pdf(s) to be processed.
  204. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  205. use_doc_unwarping (bool): Whether to use document unwarping.
  206. use_general_ocr (bool): Whether to use general OCR.
  207. use_seal_recognition (bool): Whether to use seal recognition.
  208. use_table_recognition (bool): Whether to use table recognition.
  209. **kwargs: Additional keyword arguments.
  210. Returns:
  211. LayoutParsingResult: The predicted layout parsing result.
  212. """
  213. input_params = {
  214. "use_doc_preprocessor": self.use_doc_preprocessor,
  215. "use_doc_orientation_classify": use_doc_orientation_classify,
  216. "use_doc_unwarping": use_doc_unwarping,
  217. "use_general_ocr": use_general_ocr,
  218. "use_seal_recognition": use_seal_recognition,
  219. "use_table_recognition": use_table_recognition,
  220. }
  221. if use_doc_orientation_classify or use_doc_unwarping:
  222. input_params["use_doc_preprocessor"] = True
  223. else:
  224. input_params["use_doc_preprocessor"] = False
  225. if not self.check_input_params_valid(input_params):
  226. yield None
  227. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  228. image_array = self.img_reader(batch_data)[0]
  229. img_id += 1
  230. doc_preprocessor_res, doc_preprocessor_image = (
  231. self.predict_doc_preprocessor_res(image_array, input_params)
  232. )
  233. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  234. if input_params["use_general_ocr"] or input_params["use_table_recognition"]:
  235. overall_ocr_res = self.predict_overall_ocr_res(doc_preprocessor_image)
  236. else:
  237. overall_ocr_res = {}
  238. if input_params["use_general_ocr"]:
  239. text_paragraphs_ocr_res = self.get_text_paragraphs_ocr_res(
  240. overall_ocr_res, layout_det_res
  241. )
  242. else:
  243. text_paragraphs_ocr_res = {}
  244. if input_params["use_table_recognition"]:
  245. table_res_list = next(
  246. self.table_recognition_pipeline(
  247. doc_preprocessor_image,
  248. use_layout_detection=False,
  249. use_doc_orientation_classify=False,
  250. use_doc_unwarping=False,
  251. overall_ocr_res=overall_ocr_res,
  252. layout_det_res=layout_det_res,
  253. )
  254. )
  255. table_res_list = table_res_list["table_res_list"]
  256. else:
  257. table_res_list = []
  258. if input_params["use_seal_recognition"]:
  259. seal_res_list = next(
  260. self.seal_recognition_pipeline(
  261. doc_preprocessor_image,
  262. use_layout_detection=False,
  263. use_doc_orientation_classify=False,
  264. use_doc_unwarping=False,
  265. layout_det_res=layout_det_res,
  266. )
  267. )
  268. seal_res_list = seal_res_list["seal_res_list"]
  269. else:
  270. seal_res_list = []
  271. single_img_res = {
  272. "layout_det_res": layout_det_res,
  273. "doc_preprocessor_res": doc_preprocessor_res,
  274. "overall_ocr_res": overall_ocr_res,
  275. "text_paragraphs_ocr_res": text_paragraphs_ocr_res,
  276. "table_res_list": table_res_list,
  277. "seal_res_list": seal_res_list,
  278. "input_params": input_params,
  279. "img_id": img_id,
  280. }
  281. yield LayoutParsingResult(single_img_res)