pipeline_v2.py 18 KB

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