pipeline_v2.py 17 KB

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