pipeline_v2.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. overall_ocr_res["dt_polys"].extend(sub_ocr_res["dt_polys"])
  272. overall_ocr_res["rec_texts"].extend(sub_ocr_res["rec_texts"])
  273. overall_ocr_res["rec_boxes"] = np.concatenate(
  274. [overall_ocr_res["rec_boxes"], sub_ocr_res["rec_boxes"]], axis=0
  275. )
  276. overall_ocr_res["rec_polys"].extend(sub_ocr_res["rec_polys"])
  277. overall_ocr_res["rec_scores"].extend(sub_ocr_res["rec_scores"])
  278. for formula_res in formula_res_list:
  279. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  280. poly_points = [
  281. (x_min, y_min),
  282. (x_max, y_min),
  283. (x_max, y_max),
  284. (x_min, y_max),
  285. ]
  286. overall_ocr_res["dt_polys"].append(poly_points)
  287. overall_ocr_res["rec_texts"].append(f"${formula_res['rec_formula']}$")
  288. overall_ocr_res["rec_boxes"] = np.vstack(
  289. (overall_ocr_res["rec_boxes"], [formula_res["dt_polys"]])
  290. )
  291. overall_ocr_res["rec_polys"].append(poly_points)
  292. overall_ocr_res["rec_scores"].append(1)
  293. parsing_res_list = get_single_block_parsing_res(
  294. overall_ocr_res=overall_ocr_res,
  295. layout_det_res=layout_det_res,
  296. table_res_list=table_res_list,
  297. seal_res_list=seal_res_list,
  298. )
  299. return parsing_res_list
  300. def get_model_settings(
  301. self,
  302. use_doc_orientation_classify: Union[bool, None],
  303. use_doc_unwarping: Union[bool, None],
  304. use_general_ocr: Union[bool, None],
  305. use_seal_recognition: Union[bool, None],
  306. use_table_recognition: Union[bool, None],
  307. use_formula_recognition: Union[bool, None],
  308. ) -> dict:
  309. """
  310. Get the model settings based on the provided parameters or default values.
  311. Args:
  312. use_doc_orientation_classify (Union[bool, None]): Enables document orientation classification if True. Defaults to system setting if None.
  313. use_doc_unwarping (Union[bool, None]): Enables document unwarping if True. Defaults to system setting if None.
  314. use_general_ocr (Union[bool, None]): Enables general OCR if True. Defaults to system setting if None.
  315. use_seal_recognition (Union[bool, None]): Enables seal recognition if True. Defaults to system setting if None.
  316. use_table_recognition (Union[bool, None]): Enables table recognition if True. Defaults to system setting if None.
  317. use_formula_recognition (Union[bool, None]): Enables formula recognition if True. Defaults to system setting if None.
  318. Returns:
  319. dict: A dictionary containing the model settings.
  320. """
  321. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  322. use_doc_preprocessor = self.use_doc_preprocessor
  323. else:
  324. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  325. use_doc_preprocessor = True
  326. else:
  327. use_doc_preprocessor = False
  328. if use_general_ocr is None:
  329. use_general_ocr = self.use_general_ocr
  330. if use_seal_recognition is None:
  331. use_seal_recognition = self.use_seal_recognition
  332. if use_table_recognition is None:
  333. use_table_recognition = self.use_table_recognition
  334. if use_formula_recognition is None:
  335. use_formula_recognition = self.use_formula_recognition
  336. return dict(
  337. use_doc_preprocessor=use_doc_preprocessor,
  338. use_general_ocr=use_general_ocr,
  339. use_seal_recognition=use_seal_recognition,
  340. use_table_recognition=use_table_recognition,
  341. use_formula_recognition=use_formula_recognition,
  342. )
  343. def predict(
  344. self,
  345. input: Union[str, list[str], np.ndarray, list[np.ndarray]],
  346. use_doc_orientation_classify: Union[bool, None] = None,
  347. use_doc_unwarping: Union[bool, None] = None,
  348. use_textline_orientation: Optional[bool] = None,
  349. use_general_ocr: Union[bool, None] = None,
  350. use_seal_recognition: Union[bool, None] = None,
  351. use_table_recognition: Union[bool, None] = None,
  352. use_formula_recognition: Union[bool, None] = None,
  353. layout_threshold: Optional[Union[float, dict]] = None,
  354. layout_nms: Optional[bool] = None,
  355. layout_unclip_ratio: Optional[Union[float, Tuple[float, float]]] = None,
  356. layout_merge_bboxes_mode: Optional[str] = None,
  357. text_det_limit_side_len: Union[int, None] = None,
  358. text_det_limit_type: Union[str, None] = None,
  359. text_det_thresh: Union[float, None] = None,
  360. text_det_box_thresh: Union[float, None] = None,
  361. text_det_unclip_ratio: Union[float, None] = None,
  362. text_rec_score_thresh: Union[float, None] = None,
  363. seal_det_limit_side_len: Union[int, None] = None,
  364. seal_det_limit_type: Union[str, None] = None,
  365. seal_det_thresh: Union[float, None] = None,
  366. seal_det_box_thresh: Union[float, None] = None,
  367. seal_det_unclip_ratio: Union[float, None] = None,
  368. seal_rec_score_thresh: Union[float, None] = None,
  369. **kwargs,
  370. ) -> LayoutParsingResultV2:
  371. """
  372. Predicts the layout parsing result for the given input.
  373. Args:
  374. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  375. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  376. use_textline_orientation (Optional[bool]): Whether to use textline orientation prediction.
  377. use_general_ocr (Optional[bool]): Whether to use general OCR.
  378. use_seal_recognition (Optional[bool]): Whether to use seal recognition.
  379. use_table_recognition (Optional[bool]): Whether to use table recognition.
  380. use_formula_recognition (Optional[bool]): Whether to use formula recognition.
  381. layout_threshold (Optional[float]): The threshold value to filter out low-confidence predictions. Default is None.
  382. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to False.
  383. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  384. Defaults to None.
  385. If it's a single number, then both width and height are used.
  386. If it's a tuple of two numbers, then they are used separately for width and height respectively.
  387. If it's None, then no unclipping will be performed.
  388. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  389. text_det_limit_side_len (Optional[int]): Maximum side length for text detection.
  390. text_det_limit_type (Optional[str]): Type of limit to apply for text detection.
  391. text_det_thresh (Optional[float]): Threshold for text detection.
  392. text_det_box_thresh (Optional[float]): Threshold for text detection boxes.
  393. text_det_unclip_ratio (Optional[float]): Ratio for unclipping text detection boxes.
  394. text_rec_score_thresh (Optional[float]): Score threshold for text recognition.
  395. seal_det_limit_side_len (Optional[int]): Maximum side length for seal detection.
  396. seal_det_limit_type (Optional[str]): Type of limit to apply for seal detection.
  397. seal_det_thresh (Optional[float]): Threshold for seal detection.
  398. seal_det_box_thresh (Optional[float]): Threshold for seal detection boxes.
  399. seal_det_unclip_ratio (Optional[float]): Ratio for unclipping seal detection boxes.
  400. seal_rec_score_thresh (Optional[float]): Score threshold for seal recognition.
  401. **kwargs (Any): Additional settings to extend functionality.
  402. Returns:
  403. LayoutParsingResultV2: The predicted layout parsing result.
  404. """
  405. model_settings = self.get_model_settings(
  406. use_doc_orientation_classify,
  407. use_doc_unwarping,
  408. use_general_ocr,
  409. use_seal_recognition,
  410. use_table_recognition,
  411. use_formula_recognition,
  412. )
  413. if not self.check_model_settings_valid(model_settings):
  414. yield {"error": "the input params for model settings are invalid!"}
  415. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  416. image_array = self.img_reader(batch_data.instances)[0]
  417. if model_settings["use_doc_preprocessor"]:
  418. doc_preprocessor_res = next(
  419. self.doc_preprocessor_pipeline(
  420. image_array,
  421. use_doc_orientation_classify=use_doc_orientation_classify,
  422. use_doc_unwarping=use_doc_unwarping,
  423. ),
  424. )
  425. else:
  426. doc_preprocessor_res = {"output_img": image_array}
  427. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  428. layout_det_res = next(
  429. self.layout_det_model(
  430. doc_preprocessor_image,
  431. threshold=layout_threshold,
  432. layout_nms=layout_nms,
  433. layout_unclip_ratio=layout_unclip_ratio,
  434. layout_merge_bboxes_mode=layout_merge_bboxes_mode,
  435. )
  436. )
  437. if model_settings["use_formula_recognition"]:
  438. formula_res_all = next(
  439. self.formula_recognition_pipeline(
  440. doc_preprocessor_image,
  441. use_layout_detection=False,
  442. use_doc_orientation_classify=False,
  443. use_doc_unwarping=False,
  444. layout_det_res=layout_det_res,
  445. ),
  446. )
  447. formula_res_list = formula_res_all["formula_res_list"]
  448. else:
  449. formula_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, :] = 255.0
  453. if (
  454. model_settings["use_general_ocr"]
  455. or model_settings["use_table_recognition"]
  456. ):
  457. overall_ocr_res = next(
  458. self.general_ocr_pipeline(
  459. doc_preprocessor_image,
  460. use_textline_orientation=use_textline_orientation,
  461. text_det_limit_side_len=text_det_limit_side_len,
  462. text_det_limit_type=text_det_limit_type,
  463. text_det_thresh=text_det_thresh,
  464. text_det_box_thresh=text_det_box_thresh,
  465. text_det_unclip_ratio=text_det_unclip_ratio,
  466. text_rec_score_thresh=text_rec_score_thresh,
  467. ),
  468. )
  469. else:
  470. overall_ocr_res = {}
  471. if model_settings["use_table_recognition"]:
  472. table_res_all = next(
  473. self.table_recognition_pipeline(
  474. doc_preprocessor_image,
  475. use_doc_orientation_classify=False,
  476. use_doc_unwarping=False,
  477. use_layout_detection=False,
  478. use_ocr_model=False,
  479. overall_ocr_res=overall_ocr_res,
  480. layout_det_res=layout_det_res,
  481. cell_sort_by_y_projection=True,
  482. ),
  483. )
  484. table_res_list = table_res_all["table_res_list"]
  485. else:
  486. table_res_list = []
  487. if model_settings["use_seal_recognition"]:
  488. seal_res_all = next(
  489. self.seal_recognition_pipeline(
  490. doc_preprocessor_image,
  491. use_doc_orientation_classify=False,
  492. use_doc_unwarping=False,
  493. use_layout_detection=False,
  494. layout_det_res=layout_det_res,
  495. seal_det_limit_side_len=seal_det_limit_side_len,
  496. seal_det_limit_type=seal_det_limit_type,
  497. seal_det_thresh=seal_det_thresh,
  498. seal_det_box_thresh=seal_det_box_thresh,
  499. seal_det_unclip_ratio=seal_det_unclip_ratio,
  500. seal_rec_score_thresh=seal_rec_score_thresh,
  501. ),
  502. )
  503. seal_res_list = seal_res_all["seal_res_list"]
  504. else:
  505. seal_res_list = []
  506. parsing_res_list = self.get_layout_parsing_res(
  507. doc_preprocessor_image,
  508. layout_det_res=layout_det_res,
  509. overall_ocr_res=overall_ocr_res,
  510. table_res_list=table_res_list,
  511. seal_res_list=seal_res_list,
  512. formula_res_list=formula_res_list,
  513. text_det_limit_side_len=text_det_limit_side_len,
  514. text_det_limit_type=text_det_limit_type,
  515. text_det_thresh=text_det_thresh,
  516. text_det_box_thresh=text_det_box_thresh,
  517. text_det_unclip_ratio=text_det_unclip_ratio,
  518. text_rec_score_thresh=text_rec_score_thresh,
  519. )
  520. for formula_res in formula_res_list:
  521. x_min, y_min, x_max, y_max = list(map(int, formula_res["dt_polys"]))
  522. doc_preprocessor_image[y_min:y_max, x_min:x_max, :] = formula_res[
  523. "input_img"
  524. ]
  525. single_img_res = {
  526. "input_path": batch_data.input_paths[0],
  527. "page_index": batch_data.page_indexes[0],
  528. "doc_preprocessor_res": doc_preprocessor_res,
  529. "layout_det_res": layout_det_res,
  530. "overall_ocr_res": overall_ocr_res,
  531. "table_res_list": table_res_list,
  532. "seal_res_list": seal_res_list,
  533. "formula_res_list": formula_res_list,
  534. "parsing_res_list": parsing_res_list,
  535. "model_settings": model_settings,
  536. }
  537. yield LayoutParsingResultV2(single_img_res)