pipeline_v2.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. Get 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. layout_det_res (DetResult): The layout detection results.
  200. overall_ocr_res (OCRResult): The overall OCR results.
  201. table_res_list (list): A list of table detection results.
  202. seal_res_list (list): A list of seal detection results.
  203. Returns:
  204. list: A list of dictionaries representing the layout parsing result.
  205. """
  206. layout_parsing_res = get_single_block_parsing_res(
  207. overall_ocr_res=overall_ocr_res,
  208. layout_det_res=layout_det_res,
  209. table_res_list=table_res_list,
  210. seal_res_list=seal_res_list,
  211. )
  212. parsing_res_list = [
  213. {
  214. "block_bbox": [0, 0, 2550, 2550],
  215. "block_size": [image.shape[1], image.shape[0]],
  216. "sub_blocks": layout_parsing_res,
  217. },
  218. ]
  219. return parsing_res_list
  220. def get_model_settings(
  221. self,
  222. use_doc_orientation_classify: Union[bool, None],
  223. use_doc_unwarping: Union[bool, None],
  224. use_general_ocr: Union[bool, None],
  225. use_seal_recognition: Union[bool, None],
  226. use_table_recognition: Union[bool, None],
  227. use_formula_recognition: Union[bool, None],
  228. ) -> dict:
  229. """
  230. Get the model settings based on the provided parameters or default values.
  231. Args:
  232. use_doc_orientation_classify (Union[bool, None]): Enables document orientation classification if True. Defaults to system setting if None.
  233. use_doc_unwarping (Union[bool, None]): Enables document unwarping if True. Defaults to system setting if None.
  234. use_general_ocr (Union[bool, None]): Enables general OCR if True. Defaults to system setting if None.
  235. use_seal_recognition (Union[bool, None]): Enables seal recognition if True. Defaults to system setting if None.
  236. use_table_recognition (Union[bool, None]): Enables table recognition if True. Defaults to system setting if None.
  237. use_formula_recognition (Union[bool, None]): Enables formula recognition if True. Defaults to system setting if None.
  238. Returns:
  239. dict: A dictionary containing the model settings.
  240. """
  241. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  242. use_doc_preprocessor = self.use_doc_preprocessor
  243. else:
  244. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  245. use_doc_preprocessor = True
  246. else:
  247. use_doc_preprocessor = False
  248. if use_general_ocr is None:
  249. use_general_ocr = self.use_general_ocr
  250. if use_seal_recognition is None:
  251. use_seal_recognition = self.use_seal_recognition
  252. if use_table_recognition is None:
  253. use_table_recognition = self.use_table_recognition
  254. if use_formula_recognition is None:
  255. use_formula_recognition = self.use_formula_recognition
  256. return dict(
  257. use_doc_preprocessor=use_doc_preprocessor,
  258. use_general_ocr=use_general_ocr,
  259. use_seal_recognition=use_seal_recognition,
  260. use_table_recognition=use_table_recognition,
  261. use_formula_recognition=use_formula_recognition,
  262. )
  263. def predict(
  264. self,
  265. input: Union[str, list[str], np.ndarray, list[np.ndarray]],
  266. use_doc_orientation_classify: Union[bool, None] = None,
  267. use_doc_unwarping: Union[bool, None] = None,
  268. use_textline_orientation: Optional[bool] = None,
  269. use_general_ocr: Union[bool, None] = None,
  270. use_seal_recognition: Union[bool, None] = None,
  271. use_table_recognition: Union[bool, None] = None,
  272. use_formula_recognition: Union[bool, None] = None,
  273. layout_threshold: Optional[Union[float, dict]] = None,
  274. layout_nms: Optional[bool] = None,
  275. layout_unclip_ratio: Optional[Union[float, Tuple[float, float]]] = None,
  276. layout_merge_bboxes_mode: Optional[str] = None,
  277. text_det_limit_side_len: Union[int, None] = None,
  278. text_det_limit_type: Union[str, None] = None,
  279. text_det_thresh: Union[float, None] = None,
  280. text_det_box_thresh: Union[float, None] = None,
  281. text_det_unclip_ratio: Union[float, None] = None,
  282. text_rec_score_thresh: Union[float, None] = None,
  283. seal_det_limit_side_len: Union[int, None] = None,
  284. seal_det_limit_type: Union[str, None] = None,
  285. seal_det_thresh: Union[float, None] = None,
  286. seal_det_box_thresh: Union[float, None] = None,
  287. seal_det_unclip_ratio: Union[float, None] = None,
  288. seal_rec_score_thresh: Union[float, None] = None,
  289. **kwargs,
  290. ) -> LayoutParsingResultV2:
  291. """
  292. Predicts the layout parsing result for the given input.
  293. Args:
  294. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  295. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  296. use_textline_orientation (Optional[bool]): Whether to use textline orientation prediction.
  297. use_general_ocr (Optional[bool]): Whether to use general OCR.
  298. use_seal_recognition (Optional[bool]): Whether to use seal recognition.
  299. use_table_recognition (Optional[bool]): Whether to use table recognition.
  300. use_formula_recognition (Optional[bool]): Whether to use formula recognition.
  301. layout_threshold (Optional[float]): The threshold value to filter out low-confidence predictions. Default is None.
  302. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to False.
  303. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  304. Defaults to None.
  305. If it's a single number, then both width and height are used.
  306. If it's a tuple of two numbers, then they are used separately for width and height respectively.
  307. If it's None, then no unclipping will be performed.
  308. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  309. text_det_limit_side_len (Optional[int]): Maximum side length for text detection.
  310. text_det_limit_type (Optional[str]): Type of limit to apply for text detection.
  311. text_det_thresh (Optional[float]): Threshold for text detection.
  312. text_det_box_thresh (Optional[float]): Threshold for text detection boxes.
  313. text_det_unclip_ratio (Optional[float]): Ratio for unclipping text detection boxes.
  314. text_rec_score_thresh (Optional[float]): Score threshold for text recognition.
  315. seal_det_limit_side_len (Optional[int]): Maximum side length for seal detection.
  316. seal_det_limit_type (Optional[str]): Type of limit to apply for seal detection.
  317. seal_det_thresh (Optional[float]): Threshold for seal detection.
  318. seal_det_box_thresh (Optional[float]): Threshold for seal detection boxes.
  319. seal_det_unclip_ratio (Optional[float]): Ratio for unclipping seal detection boxes.
  320. seal_rec_score_thresh (Optional[float]): Score threshold for seal recognition.
  321. **kwargs (Any): Additional settings to extend functionality.
  322. Returns:
  323. LayoutParsingResultV2: The predicted layout parsing result.
  324. """
  325. model_settings = self.get_model_settings(
  326. use_doc_orientation_classify,
  327. use_doc_unwarping,
  328. use_general_ocr,
  329. use_seal_recognition,
  330. use_table_recognition,
  331. use_formula_recognition,
  332. )
  333. if not self.check_model_settings_valid(model_settings):
  334. yield {"error": "the input params for model settings are invalid!"}
  335. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  336. image_array = self.img_reader(batch_data.instances)[0]
  337. if model_settings["use_doc_preprocessor"]:
  338. doc_preprocessor_res = next(
  339. self.doc_preprocessor_pipeline(
  340. image_array,
  341. use_doc_orientation_classify=use_doc_orientation_classify,
  342. use_doc_unwarping=use_doc_unwarping,
  343. ),
  344. )
  345. else:
  346. doc_preprocessor_res = {"output_img": image_array}
  347. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  348. layout_det_res = next(
  349. self.layout_det_model(
  350. doc_preprocessor_image,
  351. threshold=layout_threshold,
  352. layout_nms=layout_nms,
  353. layout_unclip_ratio=layout_unclip_ratio,
  354. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  355. )
  356. )
  357. if model_settings["use_formula_recognition"]:
  358. formula_res_all = next(
  359. self.formula_recognition_pipeline(
  360. doc_preprocessor_image,
  361. use_layout_detection=False,
  362. use_doc_orientation_classify=False,
  363. use_doc_unwarping=False,
  364. layout_det_res=layout_det_res,
  365. ),
  366. )
  367. formula_res_list = formula_res_all["formula_res_list"]
  368. else:
  369. formula_res_list = []
  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. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = 255.0
  373. if (
  374. model_settings["use_general_ocr"]
  375. or model_settings["use_table_recognition"]
  376. ):
  377. overall_ocr_res = next(
  378. self.general_ocr_pipeline(
  379. doc_preprocessor_image,
  380. use_textline_orientation=use_textline_orientation,
  381. text_det_limit_side_len=text_det_limit_side_len,
  382. text_det_limit_type=text_det_limit_type,
  383. text_det_thresh=text_det_thresh,
  384. text_det_box_thresh=text_det_box_thresh,
  385. text_det_unclip_ratio=text_det_unclip_ratio,
  386. text_rec_score_thresh=text_rec_score_thresh,
  387. ),
  388. )
  389. for formula_res in formula_res_list:
  390. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  391. poly_points = [
  392. (x_min, y_min),
  393. (x_max, y_min),
  394. (x_max, y_max),
  395. (x_min, y_max),
  396. ]
  397. overall_ocr_res["dt_polys"].append(poly_points)
  398. overall_ocr_res["rec_texts"].append(
  399. f"${formula_res['rec_formula']}$"
  400. )
  401. overall_ocr_res["rec_boxes"] = np.vstack(
  402. (overall_ocr_res["rec_boxes"], [formula_res["dt_polys"]])
  403. )
  404. overall_ocr_res["rec_polys"].append(poly_points)
  405. overall_ocr_res["rec_scores"].append(1)
  406. else:
  407. overall_ocr_res = {}
  408. if model_settings["use_general_ocr"]:
  409. text_paragraphs_ocr_res = self.get_text_paragraphs_ocr_res(
  410. overall_ocr_res,
  411. layout_det_res,
  412. )
  413. else:
  414. text_paragraphs_ocr_res = {}
  415. if model_settings["use_table_recognition"]:
  416. table_res_all = next(
  417. self.table_recognition_pipeline(
  418. doc_preprocessor_image,
  419. use_doc_orientation_classify=False,
  420. use_doc_unwarping=False,
  421. use_layout_detection=False,
  422. use_ocr_model=False,
  423. overall_ocr_res=overall_ocr_res,
  424. layout_det_res=layout_det_res,
  425. cell_sort_by_y_projection=True,
  426. ),
  427. )
  428. table_res_list = table_res_all["table_res_list"]
  429. else:
  430. table_res_list = []
  431. if model_settings["use_seal_recognition"]:
  432. seal_res_all = next(
  433. self.seal_recognition_pipeline(
  434. doc_preprocessor_image,
  435. use_doc_orientation_classify=False,
  436. use_doc_unwarping=False,
  437. use_layout_detection=False,
  438. layout_det_res=layout_det_res,
  439. seal_det_limit_side_len=seal_det_limit_side_len,
  440. seal_det_limit_type=seal_det_limit_type,
  441. seal_det_thresh=seal_det_thresh,
  442. seal_det_box_thresh=seal_det_box_thresh,
  443. seal_det_unclip_ratio=seal_det_unclip_ratio,
  444. seal_rec_score_thresh=seal_rec_score_thresh,
  445. ),
  446. )
  447. seal_res_list = seal_res_all["seal_res_list"]
  448. else:
  449. seal_res_list = []
  450. for formula_res in formula_res_list:
  451. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  452. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = formula_res[
  453. "input_img"
  454. ]
  455. parsing_res_list = self.get_layout_parsing_res(
  456. doc_preprocessor_image,
  457. layout_det_res=layout_det_res,
  458. overall_ocr_res=overall_ocr_res,
  459. table_res_list=table_res_list,
  460. seal_res_list=seal_res_list,
  461. )
  462. single_img_res = {
  463. "input_path": batch_data.input_paths[0],
  464. "page_index": batch_data.page_indexes[0],
  465. "doc_preprocessor_res": doc_preprocessor_res,
  466. "layout_det_res": layout_det_res,
  467. "overall_ocr_res": overall_ocr_res,
  468. "text_paragraphs_ocr_res": text_paragraphs_ocr_res,
  469. "table_res_list": table_res_list,
  470. "seal_res_list": seal_res_list,
  471. "formula_res_list": formula_res_list,
  472. "parsing_res_list": parsing_res_list,
  473. "model_settings": model_settings,
  474. }
  475. yield LayoutParsingResultV2(single_img_res)