pipeline.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. import os, sys
  15. from typing import Any, Dict, Optional
  16. import numpy as np
  17. import cv2
  18. from ..base import BasePipeline
  19. from ..components import CropByBoxes
  20. from .utils import get_neighbor_boxes_idx
  21. from .table_recognition_post_processing import get_table_recognition_res
  22. from .result import SingleTableRecognitionResult, TableRecognitionResult
  23. from ....utils import logging
  24. from ...utils.pp_option import PaddlePredictorOption
  25. from ...common.reader import ReadImage
  26. from ...common.batch_sampler import ImageBatchSampler
  27. from ..ocr.result import OCRResult
  28. from ..doc_preprocessor.result import DocPreprocessorResult
  29. # [TODO] 待更新models_new到models
  30. from ...models_new.object_detection.result import DetResult
  31. class TableRecognitionPipeline(BasePipeline):
  32. """Table Recognition Pipeline"""
  33. entities = ["table_recognition"]
  34. def __init__(
  35. self,
  36. config: Dict,
  37. device: str = None,
  38. pp_option: PaddlePredictorOption = None,
  39. use_hpip: bool = False,
  40. hpi_params: Optional[Dict[str, Any]] = None,
  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. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  49. """
  50. super().__init__(
  51. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  52. )
  53. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  54. if self.use_doc_preprocessor:
  55. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  56. "DocPreprocessor",
  57. {
  58. "pipeline_config_error": "config error for doc_preprocessor_pipeline!"
  59. },
  60. )
  61. self.doc_preprocessor_pipeline = self.create_pipeline(
  62. doc_preprocessor_config
  63. )
  64. self.use_layout_detection = config.get("use_layout_detection", True)
  65. if self.use_layout_detection:
  66. layout_det_config = config.get("SubModules", {}).get(
  67. "LayoutDetection",
  68. {"model_config_error": "config error for layout_det_model!"},
  69. )
  70. self.layout_det_model = self.create_model(layout_det_config)
  71. table_structure_config = config.get("SubModules", {}).get(
  72. "TableStructureRecognition",
  73. {"model_config_error": "config error for table_structure_model!"},
  74. )
  75. self.table_structure_model = self.create_model(table_structure_config)
  76. self.use_ocr_model = config.get("use_ocr_model", True)
  77. if self.use_ocr_model:
  78. general_ocr_config = config.get("SubPipelines", {}).get(
  79. "GeneralOCR",
  80. {"pipeline_config_error": "config error for general_ocr_pipeline!"},
  81. )
  82. self.general_ocr_pipeline = self.create_pipeline(general_ocr_config)
  83. self._crop_by_boxes = CropByBoxes()
  84. self.batch_sampler = ImageBatchSampler(batch_size=1)
  85. self.img_reader = ReadImage(format="BGR")
  86. def get_model_settings(
  87. self,
  88. use_doc_orientation_classify: Optional[bool],
  89. use_doc_unwarping: Optional[bool],
  90. use_layout_detection: Optional[bool],
  91. use_ocr_model: Optional[bool],
  92. ) -> dict:
  93. """
  94. Get the model settings based on the provided parameters or default values.
  95. Args:
  96. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  97. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  98. use_layout_detection (Optional[bool]): Whether to use layout detection.
  99. use_ocr_model (Optional[bool]): Whether to use OCR model.
  100. Returns:
  101. dict: A dictionary containing the model settings.
  102. """
  103. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  104. use_doc_preprocessor = self.use_doc_preprocessor
  105. else:
  106. use_doc_preprocessor = True
  107. if use_layout_detection is None:
  108. use_layout_detection = self.use_layout_detection
  109. if use_ocr_model is None:
  110. use_ocr_model = self.use_ocr_model
  111. return dict(
  112. use_doc_preprocessor=use_doc_preprocessor,
  113. use_layout_detection=use_layout_detection,
  114. use_ocr_model=use_ocr_model,
  115. )
  116. def check_model_settings_valid(
  117. self,
  118. model_settings: Dict,
  119. overall_ocr_res: OCRResult,
  120. layout_det_res: DetResult,
  121. ) -> bool:
  122. """
  123. Check if the input parameters are valid based on the initialized models.
  124. Args:
  125. model_settings (Dict): A dictionary containing input parameters.
  126. overall_ocr_res (OCRResult): Overall OCR result obtained after running the OCR pipeline.
  127. The overall OCR result with convert_points_to_boxes information.
  128. layout_det_res (DetResult): The layout detection result.
  129. Returns:
  130. bool: True if all required models are initialized according to input parameters, False otherwise.
  131. """
  132. if model_settings["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  133. logging.error(
  134. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  135. )
  136. return False
  137. if model_settings["use_layout_detection"]:
  138. if layout_det_res is not None:
  139. logging.error(
  140. "The layout detection model has already been initialized, please set use_layout_detection=False"
  141. )
  142. return False
  143. if not self.use_layout_detection:
  144. logging.error(
  145. "Set use_layout_detection, but the models for layout detection are not initialized."
  146. )
  147. return False
  148. if model_settings["use_ocr_model"]:
  149. if overall_ocr_res is not None:
  150. logging.error(
  151. "The OCR models have already been initialized, please set use_ocr_model=False"
  152. )
  153. return False
  154. if not self.use_ocr_model:
  155. logging.error(
  156. "Set use_ocr_model, but the models for OCR are not initialized."
  157. )
  158. return False
  159. else:
  160. if overall_ocr_res is None:
  161. logging.error("Set use_ocr_model=False, but no OCR results were found.")
  162. return False
  163. return True
  164. def predict_doc_preprocessor_res(
  165. self, image_array: np.ndarray, input_params: dict
  166. ) -> tuple[DocPreprocessorResult, np.ndarray]:
  167. """
  168. Preprocess the document image based on input parameters.
  169. Args:
  170. image_array (np.ndarray): The input image array.
  171. input_params (dict): Dictionary containing preprocessing parameters.
  172. Returns:
  173. tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
  174. result dictionary and the processed image array.
  175. """
  176. if input_params["use_doc_preprocessor"]:
  177. use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
  178. use_doc_unwarping = input_params["use_doc_unwarping"]
  179. doc_preprocessor_res = next(
  180. self.doc_preprocessor_pipeline(
  181. image_array,
  182. use_doc_orientation_classify=use_doc_orientation_classify,
  183. use_doc_unwarping=use_doc_unwarping,
  184. )
  185. )
  186. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  187. else:
  188. doc_preprocessor_res = {}
  189. doc_preprocessor_image = image_array
  190. return doc_preprocessor_res, doc_preprocessor_image
  191. def predict_single_table_recognition_res(
  192. self,
  193. image_array: np.ndarray,
  194. overall_ocr_res: OCRResult,
  195. table_box: list,
  196. flag_find_nei_text: bool = True,
  197. ) -> SingleTableRecognitionResult:
  198. """
  199. Predict table recognition results from an image array, layout detection results, and OCR results.
  200. Args:
  201. image_array (np.ndarray): The input image represented as a numpy array.
  202. overall_ocr_res (OCRResult): Overall OCR result obtained after running the OCR pipeline.
  203. The overall OCR results containing text recognition information.
  204. table_box (list): The table box coordinates.
  205. flag_find_nei_text (bool): Whether to find neighboring text.
  206. Returns:
  207. SingleTableRecognitionResult: single table recognition result.
  208. """
  209. table_structure_pred = next(self.table_structure_model(image_array))
  210. single_table_recognition_res = get_table_recognition_res(
  211. table_box, table_structure_pred, overall_ocr_res
  212. )
  213. neighbor_text = ""
  214. if flag_find_nei_text:
  215. match_idx_list = get_neighbor_boxes_idx(
  216. overall_ocr_res["rec_boxes"], table_box
  217. )
  218. if len(match_idx_list) > 0:
  219. for idx in match_idx_list:
  220. neighbor_text += overall_ocr_res["rec_texts"][idx] + "; "
  221. single_table_recognition_res["neighbor_text"] = neighbor_text
  222. return single_table_recognition_res
  223. def predict(
  224. self,
  225. input: str | list[str] | np.ndarray | list[np.ndarray],
  226. use_doc_orientation_classify: Optional[bool] = None,
  227. use_doc_unwarping: Optional[bool] = None,
  228. use_layout_detection: Optional[bool] = None,
  229. use_ocr_model: Optional[bool] = None,
  230. overall_ocr_res: Optional[OCRResult] = None,
  231. layout_det_res: Optional[DetResult] = None,
  232. text_det_limit_side_len: Optional[int] = None,
  233. text_det_limit_type: Optional[str] = None,
  234. text_det_thresh: Optional[float] = None,
  235. text_det_box_thresh: Optional[float] = None,
  236. text_det_unclip_ratio: Optional[float] = None,
  237. text_rec_score_thresh: Optional[float] = None,
  238. **kwargs,
  239. ) -> TableRecognitionResult:
  240. """
  241. This function predicts the layout parsing result for the given input.
  242. Args:
  243. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) of pdf(s) to be processed.
  244. use_layout_detection (bool): Whether to use layout detection.
  245. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  246. use_doc_unwarping (bool): Whether to use document unwarping.
  247. overall_ocr_res (OCRResult): The overall OCR result with convert_points_to_boxes information.
  248. It will be used if it is not None and use_ocr_model is False.
  249. layout_det_res (DetResult): The layout detection result.
  250. It will be used if it is not None and use_layout_detection is False.
  251. **kwargs: Additional keyword arguments.
  252. Returns:
  253. TableRecognitionResult: The predicted table recognition result.
  254. """
  255. model_settings = self.get_model_settings(
  256. use_doc_orientation_classify,
  257. use_doc_unwarping,
  258. use_layout_detection,
  259. use_ocr_model,
  260. )
  261. if not self.check_model_settings_valid(
  262. model_settings, overall_ocr_res, layout_det_res
  263. ):
  264. yield {"error": "the input params for model settings are invalid!"}
  265. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  266. if not isinstance(batch_data[0], str):
  267. # TODO: add support input_pth for ndarray and pdf
  268. input_path = f"{img_id}"
  269. else:
  270. input_path = batch_data[0]
  271. image_array = self.img_reader(batch_data)[0]
  272. if model_settings["use_doc_preprocessor"]:
  273. doc_preprocessor_res = next(
  274. self.doc_preprocessor_pipeline(
  275. image_array,
  276. use_doc_orientation_classify=use_doc_orientation_classify,
  277. use_doc_unwarping=use_doc_unwarping,
  278. )
  279. )
  280. else:
  281. doc_preprocessor_res = {"output_img": image_array}
  282. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  283. if model_settings["use_ocr_model"]:
  284. overall_ocr_res = next(
  285. self.general_ocr_pipeline(
  286. doc_preprocessor_image,
  287. text_det_limit_side_len=text_det_limit_side_len,
  288. text_det_limit_type=text_det_limit_type,
  289. text_det_thresh=text_det_thresh,
  290. text_det_box_thresh=text_det_box_thresh,
  291. text_det_unclip_ratio=text_det_unclip_ratio,
  292. text_rec_score_thresh=text_rec_score_thresh,
  293. )
  294. )
  295. table_res_list = []
  296. table_region_id = 1
  297. if not model_settings["use_layout_detection"] and layout_det_res is None:
  298. layout_det_res = {}
  299. img_height, img_width = doc_preprocessor_image.shape[:2]
  300. table_box = [0, 0, img_width - 1, img_height - 1]
  301. single_table_rec_res = self.predict_single_table_recognition_res(
  302. doc_preprocessor_image,
  303. overall_ocr_res,
  304. table_box,
  305. flag_find_nei_text=False,
  306. )
  307. single_table_rec_res["table_region_id"] = table_region_id
  308. table_res_list.append(single_table_rec_res)
  309. table_region_id += 1
  310. else:
  311. if model_settings["use_layout_detection"]:
  312. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  313. for box_info in layout_det_res["boxes"]:
  314. if box_info["label"].lower() in ["table"]:
  315. crop_img_info = self._crop_by_boxes(image_array, [box_info])
  316. crop_img_info = crop_img_info[0]
  317. table_box = crop_img_info["box"]
  318. single_table_rec_res = (
  319. self.predict_single_table_recognition_res(
  320. crop_img_info["img"], overall_ocr_res, table_box
  321. )
  322. )
  323. single_table_rec_res["table_region_id"] = table_region_id
  324. table_res_list.append(single_table_rec_res)
  325. table_region_id += 1
  326. single_img_res = {
  327. "input_path": input_path,
  328. "doc_preprocessor_res": doc_preprocessor_res,
  329. "layout_det_res": layout_det_res,
  330. "overall_ocr_res": overall_ocr_res,
  331. "table_res_list": table_res_list,
  332. "model_settings": model_settings,
  333. }
  334. yield TableRecognitionResult(single_img_res)