pipeline_v2.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. formula_res_list: list,
  195. text_det_limit_side_len: Optional[int] = None,
  196. text_det_limit_type: Optional[str] = None,
  197. text_det_thresh: Optional[float] = None,
  198. text_det_box_thresh: Optional[float] = None,
  199. text_det_unclip_ratio: Optional[float] = None,
  200. text_rec_score_thresh: Optional[float] = None,
  201. ) -> list:
  202. """
  203. Retrieves the layout parsing result based on the layout detection result, OCR result, and other recognition results.
  204. Args:
  205. image (list): The input image.
  206. layout_det_res (DetResult): The detection result containing the layout information of the document.
  207. overall_ocr_res (OCRResult): The overall OCR result containing text information.
  208. table_res_list (list): A list of table recognition results.
  209. seal_res_list (list): A list of seal recognition results.
  210. formula_res_list (list): A list of formula recognition results.
  211. text_det_limit_side_len (Optional[int], optional): The maximum side length of the text detection region. Defaults to None.
  212. text_det_limit_type (Optional[str], optional): The type of limit for the text detection region. Defaults to None.
  213. text_det_thresh (Optional[float], optional): The confidence threshold for text detection. Defaults to None.
  214. text_det_box_thresh (Optional[float], optional): The confidence threshold for text detection bounding boxes. Defaults to None
  215. text_det_unclip_ratio (Optional[float], optional): The unclip ratio for text detection. Defaults to None.
  216. text_rec_score_thresh (Optional[float], optional): The score threshold for text recognition. Defaults to None.
  217. Returns:
  218. list: A list of dictionaries representing the layout parsing result.
  219. """
  220. matched_ocr_dict = {}
  221. image = np.array(image)
  222. object_boxes = []
  223. for object_box_idx, box_info in enumerate(layout_det_res["boxes"]):
  224. box = box_info["coordinate"]
  225. label = box_info["label"].lower()
  226. object_boxes.append(box)
  227. if label not in ["formula", "table", "seal"]:
  228. _, matched_idxs = get_sub_regions_ocr_res(
  229. overall_ocr_res, [box], return_match_idx=True
  230. )
  231. for matched_idx in matched_idxs:
  232. if matched_ocr_dict.get(matched_idx, None) is None:
  233. matched_ocr_dict[matched_idx] = [object_box_idx]
  234. else:
  235. matched_ocr_dict[matched_idx].append(object_box_idx)
  236. already_processed = set()
  237. for matched_idx, layout_box_ids in matched_ocr_dict.items():
  238. if len(layout_box_ids) <= 1:
  239. continue
  240. # one ocr is matched to multiple layout boxes, split the text into multiple lines
  241. for idx in layout_box_ids:
  242. if idx in already_processed:
  243. continue
  244. already_processed.add(idx)
  245. wht_im = np.ones(image.shape, dtype=image.dtype) * 255
  246. box = object_boxes[idx]
  247. x1, y1, x2, y2 = [int(i) for i in box]
  248. wht_im[y1:y2, x1:x2, :] = image[y1:y2, x1:x2, :]
  249. sub_ocr_res = next(
  250. self.general_ocr_pipeline(
  251. wht_im,
  252. text_det_limit_side_len=text_det_limit_side_len,
  253. text_det_limit_type=text_det_limit_type,
  254. text_det_thresh=text_det_thresh,
  255. text_det_box_thresh=text_det_box_thresh,
  256. text_det_unclip_ratio=text_det_unclip_ratio,
  257. text_rec_score_thresh=text_rec_score_thresh,
  258. )
  259. )
  260. _, matched_idxs = get_sub_regions_ocr_res(
  261. overall_ocr_res, [box], return_match_idx=True
  262. )
  263. for matched_idx in sorted(matched_idxs, reverse=True):
  264. del overall_ocr_res["dt_polys"][matched_idx]
  265. del overall_ocr_res["rec_texts"][matched_idx]
  266. overall_ocr_res["rec_boxes"] = np.delete(
  267. overall_ocr_res["rec_boxes"], matched_idx, axis=0
  268. )
  269. del overall_ocr_res["rec_polys"][matched_idx]
  270. del overall_ocr_res["rec_scores"][matched_idx]
  271. if sub_ocr_res["rec_boxes"] != []:
  272. overall_ocr_res["dt_polys"].extend(sub_ocr_res["dt_polys"])
  273. overall_ocr_res["rec_texts"].extend(sub_ocr_res["rec_texts"])
  274. overall_ocr_res["rec_boxes"] = np.concatenate(
  275. [overall_ocr_res["rec_boxes"], sub_ocr_res["rec_boxes"]], axis=0
  276. )
  277. overall_ocr_res["rec_polys"].extend(sub_ocr_res["rec_polys"])
  278. overall_ocr_res["rec_scores"].extend(sub_ocr_res["rec_scores"])
  279. for formula_res in formula_res_list:
  280. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  281. poly_points = [
  282. (x_min, y_min),
  283. (x_max, y_min),
  284. (x_max, y_max),
  285. (x_min, y_max),
  286. ]
  287. overall_ocr_res["dt_polys"].append(poly_points)
  288. overall_ocr_res["rec_texts"].append(f"${formula_res['rec_formula']}$")
  289. overall_ocr_res["rec_boxes"] = np.vstack(
  290. (overall_ocr_res["rec_boxes"], [formula_res["dt_polys"]])
  291. )
  292. overall_ocr_res["rec_polys"].append(poly_points)
  293. overall_ocr_res["rec_scores"].append(1)
  294. parsing_res_list = get_single_block_parsing_res(
  295. overall_ocr_res=overall_ocr_res,
  296. layout_det_res=layout_det_res,
  297. table_res_list=table_res_list,
  298. seal_res_list=seal_res_list,
  299. )
  300. return parsing_res_list
  301. def get_model_settings(
  302. self,
  303. use_doc_orientation_classify: Union[bool, None],
  304. use_doc_unwarping: Union[bool, None],
  305. use_general_ocr: Union[bool, None],
  306. use_seal_recognition: Union[bool, None],
  307. use_table_recognition: Union[bool, None],
  308. use_formula_recognition: Union[bool, None],
  309. ) -> dict:
  310. """
  311. Get the model settings based on the provided parameters or default values.
  312. Args:
  313. use_doc_orientation_classify (Union[bool, None]): Enables document orientation classification if True. Defaults to system setting if None.
  314. use_doc_unwarping (Union[bool, None]): Enables document unwarping if True. Defaults to system setting if None.
  315. use_general_ocr (Union[bool, None]): Enables general OCR if True. Defaults to system setting if None.
  316. use_seal_recognition (Union[bool, None]): Enables seal recognition if True. Defaults to system setting if None.
  317. use_table_recognition (Union[bool, None]): Enables table recognition if True. Defaults to system setting if None.
  318. use_formula_recognition (Union[bool, None]): Enables formula recognition if True. Defaults to system setting if None.
  319. Returns:
  320. dict: A dictionary containing the model settings.
  321. """
  322. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  323. use_doc_preprocessor = self.use_doc_preprocessor
  324. else:
  325. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  326. use_doc_preprocessor = True
  327. else:
  328. use_doc_preprocessor = False
  329. if use_general_ocr is None:
  330. use_general_ocr = self.use_general_ocr
  331. if use_seal_recognition is None:
  332. use_seal_recognition = self.use_seal_recognition
  333. if use_table_recognition is None:
  334. use_table_recognition = self.use_table_recognition
  335. if use_formula_recognition is None:
  336. use_formula_recognition = self.use_formula_recognition
  337. return dict(
  338. use_doc_preprocessor=use_doc_preprocessor,
  339. use_general_ocr=use_general_ocr,
  340. use_seal_recognition=use_seal_recognition,
  341. use_table_recognition=use_table_recognition,
  342. use_formula_recognition=use_formula_recognition,
  343. )
  344. def predict(
  345. self,
  346. input: Union[str, list[str], np.ndarray, list[np.ndarray]],
  347. use_doc_orientation_classify: Union[bool, None] = None,
  348. use_doc_unwarping: Union[bool, None] = None,
  349. use_textline_orientation: Optional[bool] = None,
  350. use_general_ocr: Union[bool, None] = None,
  351. use_seal_recognition: Union[bool, None] = None,
  352. use_table_recognition: Union[bool, None] = None,
  353. use_formula_recognition: Union[bool, None] = None,
  354. layout_threshold: Optional[Union[float, dict]] = None,
  355. layout_nms: Optional[bool] = None,
  356. layout_unclip_ratio: Optional[Union[float, Tuple[float, float]]] = None,
  357. layout_merge_bboxes_mode: Optional[str] = None,
  358. text_det_limit_side_len: Union[int, None] = None,
  359. text_det_limit_type: Union[str, None] = None,
  360. text_det_thresh: Union[float, None] = None,
  361. text_det_box_thresh: Union[float, None] = None,
  362. text_det_unclip_ratio: Union[float, None] = None,
  363. text_rec_score_thresh: Union[float, None] = None,
  364. seal_det_limit_side_len: Union[int, None] = None,
  365. seal_det_limit_type: Union[str, None] = None,
  366. seal_det_thresh: Union[float, None] = None,
  367. seal_det_box_thresh: Union[float, None] = None,
  368. seal_det_unclip_ratio: Union[float, None] = None,
  369. seal_rec_score_thresh: Union[float, None] = None,
  370. **kwargs,
  371. ) -> LayoutParsingResultV2:
  372. """
  373. Predicts the layout parsing result for the given input.
  374. Args:
  375. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  376. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  377. use_textline_orientation (Optional[bool]): Whether to use textline orientation prediction.
  378. use_general_ocr (Optional[bool]): Whether to use general OCR.
  379. use_seal_recognition (Optional[bool]): Whether to use seal recognition.
  380. use_table_recognition (Optional[bool]): Whether to use table recognition.
  381. use_formula_recognition (Optional[bool]): Whether to use formula recognition.
  382. layout_threshold (Optional[float]): The threshold value to filter out low-confidence predictions. Default is None.
  383. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to False.
  384. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  385. Defaults to None.
  386. If it's a single number, then both width and height are used.
  387. If it's a tuple of two numbers, then they are used separately for width and height respectively.
  388. If it's None, then no unclipping will be performed.
  389. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  390. text_det_limit_side_len (Optional[int]): Maximum side length for text detection.
  391. text_det_limit_type (Optional[str]): Type of limit to apply for text detection.
  392. text_det_thresh (Optional[float]): Threshold for text detection.
  393. text_det_box_thresh (Optional[float]): Threshold for text detection boxes.
  394. text_det_unclip_ratio (Optional[float]): Ratio for unclipping text detection boxes.
  395. text_rec_score_thresh (Optional[float]): Score threshold for text recognition.
  396. seal_det_limit_side_len (Optional[int]): Maximum side length for seal detection.
  397. seal_det_limit_type (Optional[str]): Type of limit to apply for seal detection.
  398. seal_det_thresh (Optional[float]): Threshold for seal detection.
  399. seal_det_box_thresh (Optional[float]): Threshold for seal detection boxes.
  400. seal_det_unclip_ratio (Optional[float]): Ratio for unclipping seal detection boxes.
  401. seal_rec_score_thresh (Optional[float]): Score threshold for seal recognition.
  402. **kwargs (Any): Additional settings to extend functionality.
  403. Returns:
  404. LayoutParsingResultV2: The predicted layout parsing result.
  405. """
  406. model_settings = self.get_model_settings(
  407. use_doc_orientation_classify,
  408. use_doc_unwarping,
  409. use_general_ocr,
  410. use_seal_recognition,
  411. use_table_recognition,
  412. use_formula_recognition,
  413. )
  414. if not self.check_model_settings_valid(model_settings):
  415. yield {"error": "the input params for model settings are invalid!"}
  416. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  417. image_array = self.img_reader(batch_data.instances)[0]
  418. if model_settings["use_doc_preprocessor"]:
  419. doc_preprocessor_res = next(
  420. self.doc_preprocessor_pipeline(
  421. image_array,
  422. use_doc_orientation_classify=use_doc_orientation_classify,
  423. use_doc_unwarping=use_doc_unwarping,
  424. ),
  425. )
  426. else:
  427. doc_preprocessor_res = {"output_img": image_array}
  428. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  429. layout_det_res = next(
  430. self.layout_det_model(
  431. doc_preprocessor_image,
  432. threshold=layout_threshold,
  433. layout_nms=layout_nms,
  434. layout_unclip_ratio=layout_unclip_ratio,
  435. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  436. )
  437. )
  438. if model_settings["use_formula_recognition"]:
  439. formula_res_all = next(
  440. self.formula_recognition_pipeline(
  441. doc_preprocessor_image,
  442. use_layout_detection=False,
  443. use_doc_orientation_classify=False,
  444. use_doc_unwarping=False,
  445. layout_det_res=layout_det_res,
  446. ),
  447. )
  448. formula_res_list = formula_res_all["formula_res_list"]
  449. else:
  450. formula_res_list = []
  451. for formula_res in formula_res_list:
  452. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  453. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = 255.0
  454. if (
  455. model_settings["use_general_ocr"]
  456. or model_settings["use_table_recognition"]
  457. ):
  458. overall_ocr_res = next(
  459. self.general_ocr_pipeline(
  460. doc_preprocessor_image,
  461. use_textline_orientation=use_textline_orientation,
  462. text_det_limit_side_len=text_det_limit_side_len,
  463. text_det_limit_type=text_det_limit_type,
  464. text_det_thresh=text_det_thresh,
  465. text_det_box_thresh=text_det_box_thresh,
  466. text_det_unclip_ratio=text_det_unclip_ratio,
  467. text_rec_score_thresh=text_rec_score_thresh,
  468. ),
  469. )
  470. else:
  471. overall_ocr_res = {}
  472. if model_settings["use_table_recognition"]:
  473. table_res_all = next(
  474. self.table_recognition_pipeline(
  475. doc_preprocessor_image,
  476. use_doc_orientation_classify=False,
  477. use_doc_unwarping=False,
  478. use_layout_detection=False,
  479. use_ocr_model=False,
  480. overall_ocr_res=overall_ocr_res,
  481. layout_det_res=layout_det_res,
  482. cell_sort_by_y_projection=True,
  483. ),
  484. )
  485. table_res_list = table_res_all["table_res_list"]
  486. else:
  487. table_res_list = []
  488. if model_settings["use_seal_recognition"]:
  489. seal_res_all = next(
  490. self.seal_recognition_pipeline(
  491. doc_preprocessor_image,
  492. use_doc_orientation_classify=False,
  493. use_doc_unwarping=False,
  494. use_layout_detection=False,
  495. layout_det_res=layout_det_res,
  496. seal_det_limit_side_len=seal_det_limit_side_len,
  497. seal_det_limit_type=seal_det_limit_type,
  498. seal_det_thresh=seal_det_thresh,
  499. seal_det_box_thresh=seal_det_box_thresh,
  500. seal_det_unclip_ratio=seal_det_unclip_ratio,
  501. seal_rec_score_thresh=seal_rec_score_thresh,
  502. ),
  503. )
  504. seal_res_list = seal_res_all["seal_res_list"]
  505. else:
  506. seal_res_list = []
  507. parsing_res_list = self.get_layout_parsing_res(
  508. doc_preprocessor_image,
  509. layout_det_res=layout_det_res,
  510. overall_ocr_res=overall_ocr_res,
  511. table_res_list=table_res_list,
  512. seal_res_list=seal_res_list,
  513. formula_res_list=formula_res_list,
  514. text_det_limit_side_len=text_det_limit_side_len,
  515. text_det_limit_type=text_det_limit_type,
  516. text_det_thresh=text_det_thresh,
  517. text_det_box_thresh=text_det_box_thresh,
  518. text_det_unclip_ratio=text_det_unclip_ratio,
  519. text_rec_score_thresh=text_rec_score_thresh,
  520. )
  521. for formula_res in formula_res_list:
  522. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  523. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = formula_res[
  524. "input_img"
  525. ]
  526. single_img_res = {
  527. "input_path": batch_data.input_paths[0],
  528. "page_index": batch_data.page_indexes[0],
  529. "doc_preprocessor_res": doc_preprocessor_res,
  530. "layout_det_res": layout_det_res,
  531. "overall_ocr_res": overall_ocr_res,
  532. "table_res_list": table_res_list,
  533. "seal_res_list": seal_res_list,
  534. "formula_res_list": formula_res_list,
  535. "parsing_res_list": parsing_res_list,
  536. "model_settings": model_settings,
  537. }
  538. yield LayoutParsingResultV2(single_img_res)