pipeline.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 ..base import BasePipeline
  15. from typing import Any, Dict, Optional
  16. import numpy as np
  17. import cv2
  18. from ..components import CropByBoxes
  19. from .utils import convert_points_to_boxes, get_sub_regions_ocr_res
  20. from .table_recognition_post_processing import get_table_recognition_res
  21. from .result import LayoutParsingResult
  22. from ....utils import logging
  23. from ...utils.pp_option import PaddlePredictorOption
  24. ########## [TODO]后续需要更新路径
  25. from ...components.transforms import ReadImage
  26. from ..ocr.result import OCRResult
  27. from ...results import DetResult
  28. class LayoutParsingPipeline(BasePipeline):
  29. """Layout Parsing Pipeline"""
  30. entities = ["layout_parsing", "seal_recognition", "table_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_params: Optional[Dict[str, Any]] = None,
  38. ) -> None:
  39. """Initializes the layout parsing 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 high-performance inference (hpip) for prediction. Defaults to False.
  45. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  46. """
  47. super().__init__(
  48. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  49. )
  50. self.inintial_predictor(config)
  51. self.img_reader = ReadImage(format="BGR")
  52. self._crop_by_boxes = CropByBoxes()
  53. def set_used_models_flag(self, config: Dict) -> None:
  54. """
  55. Set the flags for which models to use based on the configuration.
  56. Args:
  57. config (Dict): A dictionary containing configuration settings.
  58. Returns:
  59. None
  60. """
  61. pipeline_name = config["pipeline_name"]
  62. self.pipeline_name = pipeline_name
  63. self.use_doc_preprocessor = False
  64. self.use_general_ocr = False
  65. self.use_seal_recognition = False
  66. self.use_table_recognition = False
  67. if "use_doc_preprocessor" in config:
  68. self.use_doc_preprocessor = config["use_doc_preprocessor"]
  69. if pipeline_name == "layout_parsing":
  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. elif pipeline_name == "seal_recognition":
  77. self.use_seal_recognition = True
  78. elif pipeline_name == "table_recognition":
  79. self.use_table_recognition = True
  80. def inintial_predictor(self, config: Dict) -> None:
  81. """Initializes the predictor based on the provided configuration.
  82. Args:
  83. config (Dict): A dictionary containing the configuration for the predictor.
  84. Returns:
  85. None
  86. """
  87. self.set_used_models_flag(config)
  88. layout_det_config = config["SubModules"]["LayoutDetection"]
  89. self.layout_det_model = self.create_model(layout_det_config)
  90. if self.use_doc_preprocessor:
  91. doc_preprocessor_config = config["SubPipelines"]["DocPreprocessor"]
  92. self.doc_preprocessor_pipeline = self.create_pipeline(
  93. doc_preprocessor_config
  94. )
  95. if self.use_general_ocr:
  96. general_ocr_config = config["SubPipelines"]["GeneralOCR"]
  97. self.general_ocr_pipeline = self.create_pipeline(general_ocr_config)
  98. if self.use_seal_recognition:
  99. seal_ocr_config = config["SubPipelines"]["SealOCR"]
  100. self.seal_ocr_pipeline = self.create_pipeline(seal_ocr_config)
  101. if self.use_table_recognition:
  102. table_structure_config = config["SubModules"]["TableStructureRecognition"]
  103. self.table_structure_model = self.create_model(table_structure_config)
  104. if not self.use_general_ocr:
  105. general_ocr_config = config["SubPipelines"]["GeneralOCR"]
  106. self.general_ocr_pipeline = self.create_pipeline(general_ocr_config)
  107. return
  108. def get_text_paragraphs_ocr_res(
  109. self, overall_ocr_res: OCRResult, layout_det_res: DetResult
  110. ) -> OCRResult:
  111. """
  112. Retrieves the OCR results for text paragraphs, excluding those of formulas, tables, and seals.
  113. Args:
  114. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  115. layout_det_res (DetResult): The detection result containing the layout information of the document.
  116. Returns:
  117. OCRResult: The OCR result for text paragraphs after excluding formulas, tables, and seals.
  118. """
  119. object_boxes = []
  120. for box_info in layout_det_res["boxes"]:
  121. if box_info["label"].lower() in ["formula", "table", "seal"]:
  122. object_boxes.append(box_info["coordinate"])
  123. object_boxes = np.array(object_boxes)
  124. return get_sub_regions_ocr_res(overall_ocr_res, object_boxes, flag_within=False)
  125. def check_input_params_valid(self, input_params: Dict) -> bool:
  126. """
  127. Check if the input parameters are valid based on the initialized models.
  128. Args:
  129. input_params (Dict): A dictionary containing input parameters.
  130. Returns:
  131. bool: True if all required models are initialized according to input parameters, False otherwise.
  132. """
  133. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  134. logging.error(
  135. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  136. )
  137. return False
  138. if input_params["use_general_ocr"] and not self.use_general_ocr:
  139. logging.error(
  140. "Set use_general_ocr, but the models for general OCR are not initialized."
  141. )
  142. return False
  143. if input_params["use_seal_recognition"] and not self.use_seal_recognition:
  144. logging.error(
  145. "Set use_seal_recognition, but the models for seal recognition are not initialized."
  146. )
  147. return False
  148. if input_params["use_table_recognition"] and not self.use_table_recognition:
  149. logging.error(
  150. "Set use_table_recognition, but the models for table recognition are not initialized."
  151. )
  152. return False
  153. return True
  154. def convert_input_params(self, input_params: Dict) -> None:
  155. """
  156. Convert input parameters based on the pipeline name.
  157. Args:
  158. input_params (Dict): The input parameters dictionary.
  159. Returns:
  160. None
  161. """
  162. if self.pipeline_name == "seal_recognition":
  163. input_params["use_general_ocr"] = False
  164. input_params["use_table_recognition"] = False
  165. elif self.pipeline_name == "table_recognition":
  166. input_params["use_general_ocr"] = False
  167. input_params["use_seal_recognition"] = False
  168. return
  169. def predict(
  170. self,
  171. input: str | list[str] | np.ndarray | list[np.ndarray],
  172. use_doc_orientation_classify: bool = False,
  173. use_doc_unwarping: bool = False,
  174. use_general_ocr: bool = True,
  175. use_seal_recognition: bool = True,
  176. use_table_recognition: bool = True,
  177. **kwargs
  178. ) -> LayoutParsingResult:
  179. """
  180. This function predicts the layout parsing result for the given input.
  181. Args:
  182. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) to be processed.
  183. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  184. use_doc_unwarping (bool): Whether to use document unwarping.
  185. use_general_ocr (bool): Whether to use general OCR.
  186. use_seal_recognition (bool): Whether to use seal recognition.
  187. use_table_recognition (bool): Whether to use table recognition.
  188. **kwargs: Additional keyword arguments.
  189. Returns:
  190. LayoutParsingResult: The predicted layout parsing result.
  191. """
  192. if not isinstance(input, list):
  193. input_list = [input]
  194. else:
  195. input_list = input
  196. input_params = {
  197. "use_doc_preprocessor": self.use_doc_preprocessor,
  198. "use_doc_orientation_classify": use_doc_orientation_classify,
  199. "use_doc_unwarping": use_doc_unwarping,
  200. "use_general_ocr": use_general_ocr,
  201. "use_seal_recognition": use_seal_recognition,
  202. "use_table_recognition": use_table_recognition,
  203. }
  204. self.convert_input_params(input_params)
  205. if use_doc_orientation_classify or use_doc_unwarping:
  206. input_params["use_doc_preprocessor"] = True
  207. else:
  208. input_params["use_doc_preprocessor"] = False
  209. if not self.check_input_params_valid(input_params):
  210. yield {"error": "input params invalid"}
  211. img_id = 1
  212. for input in input_list:
  213. if isinstance(input, str):
  214. image_array = next(self.img_reader(input))[0]["img"]
  215. else:
  216. image_array = input
  217. assert len(image_array.shape) == 3
  218. if input_params["use_doc_preprocessor"]:
  219. doc_preprocessor_res = next(
  220. self.doc_preprocessor_pipeline(
  221. image_array,
  222. use_doc_orientation_classify=use_doc_orientation_classify,
  223. use_doc_unwarping=use_doc_unwarping,
  224. )
  225. )
  226. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  227. doc_preprocessor_res["img_id"] = img_id
  228. else:
  229. doc_preprocessor_res = {}
  230. doc_preprocessor_image = image_array
  231. ########## [TODO]RT-DETR 检测结果有重复
  232. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  233. if input_params["use_general_ocr"] or input_params["use_table_recognition"]:
  234. overall_ocr_res = next(
  235. self.general_ocr_pipeline(doc_preprocessor_image)
  236. )
  237. overall_ocr_res["img_id"] = img_id
  238. dt_boxes = convert_points_to_boxes(overall_ocr_res["dt_polys"])
  239. overall_ocr_res["dt_boxes"] = dt_boxes
  240. else:
  241. overall_ocr_res = {}
  242. text_paragraphs_ocr_res = {}
  243. if input_params["use_general_ocr"]:
  244. text_paragraphs_ocr_res = self.get_text_paragraphs_ocr_res(
  245. overall_ocr_res, layout_det_res
  246. )
  247. text_paragraphs_ocr_res["img_id"] = img_id
  248. table_res_list = []
  249. if input_params["use_table_recognition"]:
  250. table_region_id = 1
  251. for box_info in layout_det_res["boxes"]:
  252. if box_info["label"].lower() in ["table"]:
  253. crop_img_info = self._crop_by_boxes(
  254. doc_preprocessor_image, [box_info]
  255. )
  256. crop_img_info = crop_img_info[0]
  257. table_structure_pred = next(
  258. self.table_structure_model(crop_img_info["img"])
  259. )
  260. table_recognition_res = get_table_recognition_res(
  261. crop_img_info, table_structure_pred, overall_ocr_res
  262. )
  263. table_recognition_res["table_region_id"] = table_region_id
  264. table_region_id += 1
  265. table_res_list.append(table_recognition_res)
  266. seal_res_list = []
  267. if input_params["use_seal_recognition"]:
  268. seal_region_id = 1
  269. for box_info in layout_det_res["boxes"]:
  270. if box_info["label"].lower() in ["seal"]:
  271. crop_img_info = self._crop_by_boxes(
  272. doc_preprocessor_image, [box_info]
  273. )
  274. crop_img_info = crop_img_info[0]
  275. seal_ocr_res = next(
  276. self.seal_ocr_pipeline(crop_img_info["img"])
  277. )
  278. seal_ocr_res["seal_region_id"] = seal_region_id
  279. seal_region_id += 1
  280. seal_res_list.append(seal_ocr_res)
  281. single_img_res = {
  282. "layout_det_res": layout_det_res,
  283. "doc_preprocessor_res": doc_preprocessor_res,
  284. "text_paragraphs_ocr_res": text_paragraphs_ocr_res,
  285. "table_res_list": table_res_list,
  286. "seal_res_list": seal_res_list,
  287. "input_params": input_params,
  288. }
  289. yield LayoutParsingResult(single_img_res)