pipeline_v2.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. from typing import Optional, Union, Tuple
  16. import numpy as np
  17. from ....utils import logging
  18. from ...common.batch_sampler import ImageBatchSampler
  19. from ...common.reader import ReadImage
  20. from ...models.object_detection.result import DetResult
  21. from ...utils.pp_option import PaddlePredictorOption
  22. from ..base import BasePipeline
  23. from ..ocr.result import OCRResult
  24. from .result_v2 import LayoutParsingResultV2
  25. from .utils import get_single_block_parsing_res
  26. from .utils import get_sub_regions_ocr_res
  27. class LayoutParsingPipelineV2(BasePipeline):
  28. """Layout Parsing Pipeline V2"""
  29. entities = ["layout_parsing_v2"]
  30. def __init__(
  31. self,
  32. config: dict,
  33. device: str = None,
  34. pp_option: PaddlePredictorOption = None,
  35. use_hpip: bool = False,
  36. ) -> None:
  37. """Initializes the layout parsing pipeline.
  38. Args:
  39. config (Dict): Configuration dictionary containing various settings.
  40. device (str, optional): Device to run the predictions on. Defaults to None.
  41. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  42. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  43. """
  44. super().__init__(
  45. device=device,
  46. pp_option=pp_option,
  47. use_hpip=use_hpip,
  48. )
  49. self.inintial_predictor(config)
  50. self.batch_sampler = ImageBatchSampler(batch_size=1)
  51. self.img_reader = ReadImage(format="BGR")
  52. def inintial_predictor(self, config: dict) -> None:
  53. """Initializes the predictor based on the provided configuration.
  54. Args:
  55. config (Dict): A dictionary containing the configuration for the predictor.
  56. Returns:
  57. None
  58. """
  59. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  60. self.use_general_ocr = config.get("use_general_ocr", True)
  61. self.use_table_recognition = config.get("use_table_recognition", True)
  62. self.use_seal_recognition = config.get("use_seal_recognition", True)
  63. self.use_formula_recognition = config.get(
  64. "use_formula_recognition",
  65. True,
  66. )
  67. if self.use_doc_preprocessor:
  68. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  69. "DocPreprocessor",
  70. {
  71. "pipeline_config_error": "config error for doc_preprocessor_pipeline!",
  72. },
  73. )
  74. self.doc_preprocessor_pipeline = self.create_pipeline(
  75. doc_preprocessor_config,
  76. )
  77. layout_det_config = config.get("SubModules", {}).get(
  78. "LayoutDetection",
  79. {"model_config_error": "config error for layout_det_model!"},
  80. )
  81. layout_kwargs = {}
  82. if (threshold := layout_det_config.get("threshold", None)) is not None:
  83. layout_kwargs["threshold"] = threshold
  84. if (layout_nms := layout_det_config.get("layout_nms", None)) is not None:
  85. layout_kwargs["layout_nms"] = layout_nms
  86. if (
  87. layout_unclip_ratio := layout_det_config.get("layout_unclip_ratio", None)
  88. ) is not None:
  89. layout_kwargs["layout_unclip_ratio"] = layout_unclip_ratio
  90. if (
  91. layout_merge_bboxes_mode := layout_det_config.get(
  92. "layout_merge_bboxes_mode", None
  93. )
  94. ) is not None:
  95. layout_kwargs["layout_merge_bboxes_mode"] = layout_merge_bboxes_mode
  96. self.layout_det_model = self.create_model(layout_det_config, **layout_kwargs)
  97. if self.use_general_ocr or self.use_table_recognition:
  98. general_ocr_config = config.get("SubPipelines", {}).get(
  99. "GeneralOCR",
  100. {"pipeline_config_error": "config error for general_ocr_pipeline!"},
  101. )
  102. self.general_ocr_pipeline = self.create_pipeline(
  103. general_ocr_config,
  104. )
  105. if self.use_seal_recognition:
  106. seal_recognition_config = config.get("SubPipelines", {}).get(
  107. "SealRecognition",
  108. {
  109. "pipeline_config_error": "config error for seal_recognition_pipeline!",
  110. },
  111. )
  112. self.seal_recognition_pipeline = self.create_pipeline(
  113. seal_recognition_config,
  114. )
  115. if self.use_table_recognition:
  116. table_recognition_config = config.get("SubPipelines", {}).get(
  117. "TableRecognition",
  118. {
  119. "pipeline_config_error": "config error for table_recognition_pipeline!",
  120. },
  121. )
  122. self.table_recognition_pipeline = self.create_pipeline(
  123. table_recognition_config,
  124. )
  125. if self.use_formula_recognition:
  126. formula_recognition_config = config.get("SubPipelines", {}).get(
  127. "FormulaRecognition",
  128. {
  129. "pipeline_config_error": "config error for formula_recognition_pipeline!",
  130. },
  131. )
  132. self.formula_recognition_pipeline = self.create_pipeline(
  133. formula_recognition_config,
  134. )
  135. return
  136. def get_text_paragraphs_ocr_res(
  137. self,
  138. overall_ocr_res: OCRResult,
  139. layout_det_res: DetResult,
  140. ) -> OCRResult:
  141. """
  142. Retrieves the OCR results for text paragraphs, excluding those of formulas, tables, and seals.
  143. Args:
  144. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  145. layout_det_res (DetResult): The detection result containing the layout information of the document.
  146. Returns:
  147. OCRResult: The OCR result for text paragraphs after excluding formulas, tables, and seals.
  148. """
  149. object_boxes = []
  150. for box_info in layout_det_res["boxes"]:
  151. if box_info["label"].lower() in ["formula", "table", "seal"]:
  152. object_boxes.append(box_info["coordinate"])
  153. object_boxes = np.array(object_boxes)
  154. sub_regions_ocr_res = get_sub_regions_ocr_res(
  155. overall_ocr_res, object_boxes, flag_within=False
  156. )
  157. return sub_regions_ocr_res
  158. def check_model_settings_valid(self, input_params: dict) -> bool:
  159. """
  160. Check if the input parameters are valid based on the initialized models.
  161. Args:
  162. input_params (Dict): A dictionary containing input parameters.
  163. Returns:
  164. bool: True if all required models are initialized according to input parameters, False otherwise.
  165. """
  166. if input_params["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  167. logging.error(
  168. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized.",
  169. )
  170. return False
  171. if input_params["use_general_ocr"] and not self.use_general_ocr:
  172. logging.error(
  173. "Set use_general_ocr, but the models for general OCR are not initialized.",
  174. )
  175. return False
  176. if input_params["use_seal_recognition"] and not self.use_seal_recognition:
  177. logging.error(
  178. "Set use_seal_recognition, but the models for seal recognition are not initialized.",
  179. )
  180. return False
  181. if input_params["use_table_recognition"] and not self.use_table_recognition:
  182. logging.error(
  183. "Set use_table_recognition, but the models for table recognition are not initialized.",
  184. )
  185. return False
  186. return True
  187. def get_layout_parsing_res(
  188. self,
  189. image: list,
  190. layout_det_res: DetResult,
  191. overall_ocr_res: OCRResult,
  192. table_res_list: list,
  193. seal_res_list: list,
  194. ) -> list:
  195. """
  196. Retrieves the layout parsing result based on the layout detection result, OCR result, and other recognition results.
  197. Args:
  198. image (list): The input image.
  199. overall_ocr_res (OCRResult): An object containing the overall OCR results, including detected text boxes and recognized text. The structure is expected to have:
  200. - "input_img": The image on which OCR was performed.
  201. - "dt_boxes": A list of detected text box coordinates.
  202. - "rec_texts": A list of recognized text corresponding to the detected boxes.
  203. layout_det_res (DetResult): An object containing the layout detection results, including detected layout boxes and their labels. The structure is expected to have:
  204. - "boxes": A list of dictionaries with keys "coordinate" for box coordinates and "label" for the type of content.
  205. table_res_list (list): A list of table detection results, where each item is a dictionary containing:
  206. - "layout_bbox": The bounding box of the table layout.
  207. - "pred_html": The predicted HTML representation of the table.
  208. Returns:
  209. list: A list of dictionaries representing the layout parsing result.
  210. """
  211. layout_parsing_res = get_single_block_parsing_res(
  212. overall_ocr_res=overall_ocr_res,
  213. layout_det_res=layout_det_res,
  214. table_res_list=table_res_list,
  215. seal_res_list=seal_res_list,
  216. )
  217. parsing_res_list = [
  218. {
  219. "block_bbox": [0, 0, 2550, 2550],
  220. "block_size": [image.shape[1], image.shape[0]],
  221. "sub_blocks": layout_parsing_res,
  222. },
  223. ]
  224. return parsing_res_list
  225. def get_model_settings(
  226. self,
  227. use_doc_orientation_classify: Union[bool, None],
  228. use_doc_unwarping: Union[bool, None],
  229. use_general_ocr: Union[bool, None],
  230. use_seal_recognition: Union[bool, None],
  231. use_table_recognition: Union[bool, None],
  232. use_formula_recognition: Union[bool, None],
  233. ) -> dict:
  234. """
  235. Get the model settings based on the provided parameters or default values.
  236. Args:
  237. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  238. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  239. use_general_ocr (Optional[bool]): Whether to use general OCR.
  240. use_seal_recognition (Optional[bool]): Whether to use seal recognition.
  241. use_table_recognition (Optional[bool]): Whether to use table recognition.
  242. Returns:
  243. dict: A dictionary containing the model settings.
  244. """
  245. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  246. use_doc_preprocessor = self.use_doc_preprocessor
  247. else:
  248. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  249. use_doc_preprocessor = True
  250. else:
  251. use_doc_preprocessor = False
  252. if use_general_ocr is None:
  253. use_general_ocr = self.use_general_ocr
  254. if use_seal_recognition is None:
  255. use_seal_recognition = self.use_seal_recognition
  256. if use_table_recognition is None:
  257. use_table_recognition = self.use_table_recognition
  258. if use_formula_recognition is None:
  259. use_formula_recognition = self.use_formula_recognition
  260. return dict(
  261. use_doc_preprocessor=use_doc_preprocessor,
  262. use_general_ocr=use_general_ocr,
  263. use_seal_recognition=use_seal_recognition,
  264. use_table_recognition=use_table_recognition,
  265. use_formula_recognition=use_formula_recognition,
  266. )
  267. def predict(
  268. self,
  269. input: Union[str, list[str], np.ndarray, list[np.ndarray]],
  270. use_doc_orientation_classify: Union[bool, None] = None,
  271. use_doc_unwarping: Union[bool, None] = None,
  272. use_general_ocr: Union[bool, None] = None,
  273. use_seal_recognition: Union[bool, None] = None,
  274. use_table_recognition: Union[bool, None] = None,
  275. use_formula_recognition: Union[bool, None] = None,
  276. text_det_limit_side_len: Union[int, None] = None,
  277. text_det_limit_type: Union[str, None] = None,
  278. text_det_thresh: Union[float, None] = None,
  279. text_det_box_thresh: Union[float, None] = None,
  280. text_det_unclip_ratio: Union[float, None] = None,
  281. text_rec_score_thresh: Union[float, None] = None,
  282. seal_det_limit_side_len: Union[int, None] = None,
  283. seal_det_limit_type: Union[str, None] = None,
  284. seal_det_thresh: Union[float, None] = None,
  285. seal_det_box_thresh: Union[float, None] = None,
  286. seal_det_unclip_ratio: Union[float, None] = None,
  287. seal_rec_score_thresh: Union[float, None] = None,
  288. layout_threshold: Optional[Union[float, dict]] = None,
  289. layout_nms: Optional[bool] = None,
  290. layout_unclip_ratio: Optional[Union[float, Tuple[float, float]]] = None,
  291. layout_merge_bboxes_mode: Optional[str] = None,
  292. **kwargs,
  293. ) -> LayoutParsingResultV2:
  294. """
  295. This function predicts the layout parsing result for the given input.
  296. Args:
  297. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): The input image(s) or pdf(s) to be processed.
  298. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  299. use_doc_unwarping (bool): Whether to use document unwarping.
  300. use_general_ocr (bool): Whether to use general OCR.
  301. use_seal_recognition (bool): Whether to use seal recognition.
  302. use_table_recognition (bool): Whether to use table recognition.
  303. **kwargs: Additional keyword arguments.
  304. Returns:
  305. LayoutParsingResultV2: The predicted layout parsing result.
  306. """
  307. model_settings = self.get_model_settings(
  308. use_doc_orientation_classify,
  309. use_doc_unwarping,
  310. use_general_ocr,
  311. use_seal_recognition,
  312. use_table_recognition,
  313. use_formula_recognition,
  314. )
  315. if not self.check_model_settings_valid(model_settings):
  316. yield {"error": "the input params for model settings are invalid!"}
  317. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  318. image_array = self.img_reader(batch_data.instances)[0]
  319. if model_settings["use_doc_preprocessor"]:
  320. doc_preprocessor_res = next(
  321. self.doc_preprocessor_pipeline(
  322. image_array,
  323. use_doc_orientation_classify=use_doc_orientation_classify,
  324. use_doc_unwarping=use_doc_unwarping,
  325. ),
  326. )
  327. else:
  328. doc_preprocessor_res = {"output_img": image_array}
  329. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  330. layout_det_res = next(
  331. self.layout_det_model(
  332. doc_preprocessor_image,
  333. threshold=layout_threshold,
  334. layout_nms=layout_nms,
  335. layout_unclip_ratio=layout_unclip_ratio,
  336. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  337. )
  338. )
  339. if model_settings["use_formula_recognition"]:
  340. formula_res_all = next(
  341. self.formula_recognition_pipeline(
  342. doc_preprocessor_image,
  343. use_layout_detection=False,
  344. use_doc_orientation_classify=False,
  345. use_doc_unwarping=False,
  346. layout_det_res=layout_det_res,
  347. ),
  348. )
  349. formula_res_list = formula_res_all["formula_res_list"]
  350. else:
  351. formula_res_list = []
  352. for formula_res in formula_res_list:
  353. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  354. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = 255.0
  355. if (
  356. model_settings["use_general_ocr"]
  357. or model_settings["use_table_recognition"]
  358. ):
  359. overall_ocr_res = next(
  360. self.general_ocr_pipeline(
  361. doc_preprocessor_image,
  362. text_det_limit_side_len=text_det_limit_side_len,
  363. text_det_limit_type=text_det_limit_type,
  364. text_det_thresh=text_det_thresh,
  365. text_det_box_thresh=text_det_box_thresh,
  366. text_det_unclip_ratio=text_det_unclip_ratio,
  367. text_rec_score_thresh=text_rec_score_thresh,
  368. ),
  369. )
  370. for formula_res in formula_res_list:
  371. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  372. poly_points = [
  373. (x_min, y_min),
  374. (x_max, y_min),
  375. (x_max, y_max),
  376. (x_min, y_max),
  377. ]
  378. overall_ocr_res["dt_polys"].append(poly_points)
  379. overall_ocr_res["rec_texts"].append(
  380. f"${formula_res['rec_formula']}$"
  381. )
  382. overall_ocr_res["rec_boxes"] = np.vstack(
  383. (overall_ocr_res["rec_boxes"], [formula_res["dt_polys"]])
  384. )
  385. overall_ocr_res["rec_polys"].append(poly_points)
  386. overall_ocr_res["rec_scores"].append(1)
  387. else:
  388. overall_ocr_res = {}
  389. if model_settings["use_general_ocr"]:
  390. text_paragraphs_ocr_res = self.get_text_paragraphs_ocr_res(
  391. overall_ocr_res,
  392. layout_det_res,
  393. )
  394. else:
  395. text_paragraphs_ocr_res = {}
  396. if model_settings["use_table_recognition"]:
  397. table_res_all = next(
  398. self.table_recognition_pipeline(
  399. doc_preprocessor_image,
  400. use_doc_orientation_classify=False,
  401. use_doc_unwarping=False,
  402. use_layout_detection=False,
  403. use_ocr_model=False,
  404. overall_ocr_res=overall_ocr_res,
  405. layout_det_res=layout_det_res,
  406. cell_sort_by_y_projection=True,
  407. ),
  408. )
  409. table_res_list = table_res_all["table_res_list"]
  410. else:
  411. table_res_list = []
  412. if model_settings["use_seal_recognition"]:
  413. seal_res_all = next(
  414. self.seal_recognition_pipeline(
  415. doc_preprocessor_image,
  416. use_doc_orientation_classify=False,
  417. use_doc_unwarping=False,
  418. use_layout_detection=False,
  419. layout_det_res=layout_det_res,
  420. seal_det_limit_side_len=seal_det_limit_side_len,
  421. seal_det_limit_type=seal_det_limit_type,
  422. seal_det_thresh=seal_det_thresh,
  423. seal_det_box_thresh=seal_det_box_thresh,
  424. seal_det_unclip_ratio=seal_det_unclip_ratio,
  425. seal_rec_score_thresh=seal_rec_score_thresh,
  426. ),
  427. )
  428. seal_res_list = seal_res_all["seal_res_list"]
  429. else:
  430. seal_res_list = []
  431. for formula_res in formula_res_list:
  432. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  433. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = formula_res[
  434. "input_img"
  435. ]
  436. parsing_res_list = self.get_layout_parsing_res(
  437. doc_preprocessor_image,
  438. layout_det_res=layout_det_res,
  439. overall_ocr_res=overall_ocr_res,
  440. table_res_list=table_res_list,
  441. seal_res_list=seal_res_list,
  442. )
  443. single_img_res = {
  444. "input_path": batch_data.input_paths[0],
  445. "page_index": batch_data.page_indexes[0],
  446. "doc_preprocessor_res": doc_preprocessor_res,
  447. "layout_det_res": layout_det_res,
  448. "overall_ocr_res": overall_ocr_res,
  449. "text_paragraphs_ocr_res": text_paragraphs_ocr_res,
  450. "table_res_list": table_res_list,
  451. "seal_res_list": seal_res_list,
  452. "formula_res_list": formula_res_list,
  453. "parsing_res_list": parsing_res_list,
  454. "model_settings": model_settings,
  455. }
  456. yield LayoutParsingResultV2(single_img_res)