pipeline_v2.py 27 KB

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