pipeline.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 get_sub_regions_ocr_res
  20. from ..components import convert_points_to_boxes
  21. from .result import LayoutParsingResult
  22. from ....utils import logging
  23. from ...utils.pp_option import PaddlePredictorOption
  24. from ...common.reader import ReadImage
  25. from ...common.batch_sampler import ImageBatchSampler
  26. from ..ocr.result import OCRResult
  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 inintial_predictor(self, config: Dict) -> None:
  55. """Initializes the predictor based on the provided configuration.
  56. Args:
  57. config (Dict): A dictionary containing the configuration for the predictor.
  58. Returns:
  59. None
  60. """
  61. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  62. self.use_general_ocr = config.get("use_general_ocr", True)
  63. self.use_table_recognition = config.get("use_table_recognition", True)
  64. self.use_seal_recognition = config.get("use_seal_recognition", True)
  65. self.use_formula_recognition = config.get("use_formula_recognition", True)
  66. if self.use_doc_preprocessor:
  67. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  68. "DocPreprocessor",
  69. {
  70. "pipeline_config_error": "config error for doc_preprocessor_pipeline!"
  71. },
  72. )
  73. self.doc_preprocessor_pipeline = self.create_pipeline(
  74. doc_preprocessor_config
  75. )
  76. layout_det_config = config.get("SubModules", {}).get(
  77. "LayoutDetection",
  78. {"model_config_error": "config error for layout_det_model!"},
  79. )
  80. self.layout_det_model = self.create_model(layout_det_config)
  81. if self.use_general_ocr or self.use_table_recognition:
  82. general_ocr_config = config.get("SubPipelines", {}).get(
  83. "GeneralOCR",
  84. {"pipeline_config_error": "config error for general_ocr_pipeline!"},
  85. )
  86. self.general_ocr_pipeline = self.create_pipeline(general_ocr_config)
  87. if self.use_seal_recognition:
  88. seal_recognition_config = config.get("SubPipelines", {}).get(
  89. "SealRecognition",
  90. {
  91. "pipeline_config_error": "config error for seal_recognition_pipeline!"
  92. },
  93. )
  94. self.seal_recognition_pipeline = self.create_pipeline(
  95. seal_recognition_config
  96. )
  97. if self.use_table_recognition:
  98. table_recognition_config = config.get("SubPipelines", {}).get(
  99. "TableRecognition",
  100. {
  101. "pipeline_config_error": "config error for table_recognition_pipeline!"
  102. },
  103. )
  104. self.table_recognition_pipeline = self.create_pipeline(
  105. table_recognition_config
  106. )
  107. if self.use_formula_recognition:
  108. formula_recognition_config = config.get("SubPipelines", {}).get(
  109. "FormulaRecognition",
  110. {
  111. "pipeline_config_error": "config error for formula_recognition_pipeline!"
  112. },
  113. )
  114. self.formula_recognition_pipeline = self.create_pipeline(
  115. formula_recognition_config
  116. )
  117. return
  118. def get_text_paragraphs_ocr_res(
  119. self, overall_ocr_res: OCRResult, layout_det_res: DetResult
  120. ) -> OCRResult:
  121. """
  122. Retrieves the OCR results for text paragraphs, excluding those of formulas, tables, and seals.
  123. Args:
  124. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  125. layout_det_res (DetResult): The detection result containing the layout information of the document.
  126. Returns:
  127. OCRResult: The OCR result for text paragraphs after excluding formulas, tables, and seals.
  128. """
  129. object_boxes = []
  130. for box_info in layout_det_res["boxes"]:
  131. if box_info["label"].lower() in ["formula", "table", "seal"]:
  132. object_boxes.append(box_info["coordinate"])
  133. object_boxes = np.array(object_boxes)
  134. return get_sub_regions_ocr_res(overall_ocr_res, object_boxes, flag_within=False)
  135. def check_model_settings_valid(self, input_params: Dict) -> bool:
  136. """
  137. Check if the input parameters are valid based on the initialized models.
  138. Args:
  139. input_params (Dict): A dictionary containing input parameters.
  140. Returns:
  141. bool: True if all required models are initialized according to input parameters, False otherwise.
  142. """
  143. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  144. logging.error(
  145. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  146. )
  147. return False
  148. if input_params["use_general_ocr"] and not self.use_general_ocr:
  149. logging.error(
  150. "Set use_general_ocr, but the models for general OCR are not initialized."
  151. )
  152. return False
  153. if input_params["use_seal_recognition"] and not self.use_seal_recognition:
  154. logging.error(
  155. "Set use_seal_recognition, but the models for seal recognition are not initialized."
  156. )
  157. return False
  158. if input_params["use_table_recognition"] and not self.use_table_recognition:
  159. logging.error(
  160. "Set use_table_recognition, but the models for table recognition are not initialized."
  161. )
  162. return False
  163. return True
  164. def get_model_settings(
  165. self,
  166. use_doc_orientation_classify: Optional[bool],
  167. use_doc_unwarping: Optional[bool],
  168. use_general_ocr: Optional[bool],
  169. use_seal_recognition: Optional[bool],
  170. use_table_recognition: Optional[bool],
  171. use_formula_recognition: Optional[bool],
  172. ) -> dict:
  173. """
  174. Get the model settings based on the provided parameters or default values.
  175. Args:
  176. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  177. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  178. use_general_ocr (Optional[bool]): Whether to use general OCR.
  179. use_seal_recognition (Optional[bool]): Whether to use seal recognition.
  180. use_table_recognition (Optional[bool]): Whether to use table recognition.
  181. Returns:
  182. dict: A dictionary containing the model settings.
  183. """
  184. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  185. use_doc_preprocessor = self.use_doc_preprocessor
  186. else:
  187. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  188. use_doc_preprocessor = True
  189. else:
  190. use_doc_preprocessor = False
  191. if use_general_ocr is None:
  192. use_general_ocr = self.use_general_ocr
  193. if use_seal_recognition is None:
  194. use_seal_recognition = self.use_seal_recognition
  195. if use_table_recognition is None:
  196. use_table_recognition = self.use_table_recognition
  197. if use_formula_recognition is None:
  198. use_formula_recognition = self.use_formula_recognition
  199. return dict(
  200. use_doc_preprocessor=use_doc_preprocessor,
  201. use_general_ocr=use_general_ocr,
  202. use_seal_recognition=use_seal_recognition,
  203. use_table_recognition=use_table_recognition,
  204. use_formula_recognition=use_formula_recognition,
  205. )
  206. def predict(
  207. self,
  208. input: str | list[str] | np.ndarray | list[np.ndarray],
  209. use_doc_orientation_classify: Optional[bool] = None,
  210. use_doc_unwarping: Optional[bool] = None,
  211. use_general_ocr: Optional[bool] = None,
  212. use_seal_recognition: Optional[bool] = None,
  213. use_table_recognition: Optional[bool] = None,
  214. use_formula_recognition: Optional[bool] = None,
  215. text_det_limit_side_len: Optional[int] = None,
  216. text_det_limit_type: Optional[str] = None,
  217. text_det_thresh: Optional[float] = None,
  218. text_det_box_thresh: Optional[float] = None,
  219. text_det_unclip_ratio: Optional[float] = None,
  220. text_rec_score_thresh: Optional[float] = None,
  221. seal_det_limit_side_len: Optional[int] = None,
  222. seal_det_limit_type: Optional[str] = None,
  223. seal_det_thresh: Optional[float] = None,
  224. seal_det_box_thresh: Optional[float] = None,
  225. seal_det_unclip_ratio: Optional[float] = None,
  226. seal_rec_score_thresh: Optional[float] = None,
  227. **kwargs,
  228. ) -> LayoutParsingResult:
  229. """
  230. This function predicts the layout parsing result for the given input.
  231. Args:
  232. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or pdf(s) to be processed.
  233. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  234. use_doc_unwarping (bool): Whether to use document unwarping.
  235. use_general_ocr (bool): Whether to use general OCR.
  236. use_seal_recognition (bool): Whether to use seal recognition.
  237. use_table_recognition (bool): Whether to use table recognition.
  238. **kwargs: Additional keyword arguments.
  239. Returns:
  240. LayoutParsingResult: The predicted layout parsing result.
  241. """
  242. model_settings = self.get_model_settings(
  243. use_doc_orientation_classify,
  244. use_doc_unwarping,
  245. use_general_ocr,
  246. use_seal_recognition,
  247. use_table_recognition,
  248. use_formula_recognition,
  249. )
  250. if not self.check_model_settings_valid(model_settings):
  251. yield {"error": "the input params for model settings are invalid!"}
  252. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  253. if not isinstance(batch_data[0], str):
  254. # TODO: add support input_pth for ndarray and pdf
  255. input_path = f"{img_id}"
  256. else:
  257. input_path = batch_data[0]
  258. image_array = self.img_reader(batch_data)[0]
  259. if model_settings["use_doc_preprocessor"]:
  260. doc_preprocessor_res = next(
  261. self.doc_preprocessor_pipeline(
  262. image_array,
  263. use_doc_orientation_classify=use_doc_orientation_classify,
  264. use_doc_unwarping=use_doc_unwarping,
  265. )
  266. )
  267. else:
  268. doc_preprocessor_res = {"output_img": image_array}
  269. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  270. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  271. if (
  272. model_settings["use_general_ocr"]
  273. or model_settings["use_table_recognition"]
  274. ):
  275. overall_ocr_res = next(
  276. self.general_ocr_pipeline(
  277. doc_preprocessor_image,
  278. text_det_limit_side_len=text_det_limit_side_len,
  279. text_det_limit_type=text_det_limit_type,
  280. text_det_thresh=text_det_thresh,
  281. text_det_box_thresh=text_det_box_thresh,
  282. text_det_unclip_ratio=text_det_unclip_ratio,
  283. text_rec_score_thresh=text_rec_score_thresh,
  284. )
  285. )
  286. else:
  287. overall_ocr_res = {}
  288. if model_settings["use_general_ocr"]:
  289. text_paragraphs_ocr_res = self.get_text_paragraphs_ocr_res(
  290. overall_ocr_res, layout_det_res
  291. )
  292. else:
  293. text_paragraphs_ocr_res = {}
  294. if model_settings["use_table_recognition"]:
  295. table_res_all = next(
  296. self.table_recognition_pipeline(
  297. doc_preprocessor_image,
  298. use_doc_orientation_classify=False,
  299. use_doc_unwarping=False,
  300. use_layout_detection=False,
  301. use_ocr_model=False,
  302. overall_ocr_res=overall_ocr_res,
  303. layout_det_res=layout_det_res,
  304. )
  305. )
  306. table_res_list = table_res_all["table_res_list"]
  307. else:
  308. table_res_list = []
  309. if model_settings["use_seal_recognition"]:
  310. seal_res_all = next(
  311. self.seal_recognition_pipeline(
  312. doc_preprocessor_image,
  313. use_doc_orientation_classify=False,
  314. use_doc_unwarping=False,
  315. use_layout_detection=False,
  316. layout_det_res=layout_det_res,
  317. seal_det_limit_side_len=seal_det_limit_side_len,
  318. seal_det_limit_type=seal_det_limit_type,
  319. seal_det_thresh=seal_det_thresh,
  320. seal_det_box_thresh=seal_det_box_thresh,
  321. seal_det_unclip_ratio=seal_det_unclip_ratio,
  322. seal_rec_score_thresh=seal_rec_score_thresh,
  323. )
  324. )
  325. seal_res_list = seal_res_all["seal_res_list"]
  326. else:
  327. seal_res_list = []
  328. if model_settings["use_formula_recognition"]:
  329. formula_res_all = next(
  330. self.formula_recognition_pipeline(
  331. doc_preprocessor_image,
  332. use_layout_detection=False,
  333. use_doc_orientation_classify=False,
  334. use_doc_unwarping=False,
  335. layout_det_res=layout_det_res,
  336. )
  337. )
  338. formula_res_list = formula_res_all["formula_res_list"]
  339. print(formula_res_list)
  340. else:
  341. formula_res_list = []
  342. single_img_res = {
  343. "input_path": input_path,
  344. "doc_preprocessor_res": doc_preprocessor_res,
  345. "layout_det_res": layout_det_res,
  346. "overall_ocr_res": overall_ocr_res,
  347. "text_paragraphs_ocr_res": text_paragraphs_ocr_res,
  348. "table_res_list": table_res_list,
  349. "seal_res_list": seal_res_list,
  350. "formula_res_list": formula_res_list,
  351. "model_settings": model_settings,
  352. }
  353. yield LayoutParsingResult(single_img_res)