pipeline.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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, Union, Tuple, List
  16. import numpy as np
  17. import math
  18. import cv2
  19. from ..base import BasePipeline
  20. from ..components import CropByBoxes
  21. from .utils import get_neighbor_boxes_idx
  22. from .table_recognition_post_processing import get_table_recognition_res
  23. from .result import SingleTableRecognitionResult, TableRecognitionResult
  24. from ....utils import logging
  25. from ...utils.pp_option import PaddlePredictorOption
  26. from ...common.reader import ReadImage
  27. from ...common.batch_sampler import ImageBatchSampler
  28. from ..ocr.result import OCRResult
  29. from ..doc_preprocessor.result import DocPreprocessorResult
  30. from ...models.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. ) -> None:
  41. """Initializes the layout parsing pipeline.
  42. Args:
  43. config (Dict): Configuration dictionary containing various settings.
  44. device (str, optional): Device to run the predictions on. Defaults to None.
  45. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  46. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  47. """
  48. super().__init__(device=device, pp_option=pp_option, use_hpip=use_hpip)
  49. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  50. if self.use_doc_preprocessor:
  51. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  52. "DocPreprocessor",
  53. {
  54. "pipeline_config_error": "config error for doc_preprocessor_pipeline!"
  55. },
  56. )
  57. self.doc_preprocessor_pipeline = self.create_pipeline(
  58. doc_preprocessor_config
  59. )
  60. self.use_layout_detection = config.get("use_layout_detection", True)
  61. if self.use_layout_detection:
  62. layout_det_config = config.get("SubModules", {}).get(
  63. "LayoutDetection",
  64. {"model_config_error": "config error for layout_det_model!"},
  65. )
  66. self.layout_det_model = self.create_model(layout_det_config)
  67. table_structure_config = config.get("SubModules", {}).get(
  68. "TableStructureRecognition",
  69. {"model_config_error": "config error for table_structure_model!"},
  70. )
  71. self.table_structure_model = self.create_model(table_structure_config)
  72. self.use_ocr_model = config.get("use_ocr_model", True)
  73. if self.use_ocr_model:
  74. general_ocr_config = config.get("SubPipelines", {}).get(
  75. "GeneralOCR",
  76. {"pipeline_config_error": "config error for general_ocr_pipeline!"},
  77. )
  78. self.general_ocr_pipeline = self.create_pipeline(general_ocr_config)
  79. self._crop_by_boxes = CropByBoxes()
  80. self.batch_sampler = ImageBatchSampler(batch_size=1)
  81. self.img_reader = ReadImage(format="BGR")
  82. def get_model_settings(
  83. self,
  84. use_doc_orientation_classify: Optional[bool],
  85. use_doc_unwarping: Optional[bool],
  86. use_layout_detection: Optional[bool],
  87. use_ocr_model: Optional[bool],
  88. ) -> dict:
  89. """
  90. Get the model settings based on the provided parameters or default values.
  91. Args:
  92. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  93. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  94. use_layout_detection (Optional[bool]): Whether to use layout detection.
  95. use_ocr_model (Optional[bool]): Whether to use OCR model.
  96. Returns:
  97. dict: A dictionary containing the model settings.
  98. """
  99. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  100. use_doc_preprocessor = self.use_doc_preprocessor
  101. else:
  102. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  103. use_doc_preprocessor = True
  104. else:
  105. use_doc_preprocessor = False
  106. if use_layout_detection is None:
  107. use_layout_detection = self.use_layout_detection
  108. if use_ocr_model is None:
  109. use_ocr_model = self.use_ocr_model
  110. return dict(
  111. use_doc_preprocessor=use_doc_preprocessor,
  112. use_layout_detection=use_layout_detection,
  113. use_ocr_model=use_ocr_model,
  114. )
  115. def check_model_settings_valid(
  116. self,
  117. model_settings: Dict,
  118. overall_ocr_res: OCRResult,
  119. layout_det_res: DetResult,
  120. ) -> bool:
  121. """
  122. Check if the input parameters are valid based on the initialized models.
  123. Args:
  124. model_settings (Dict): A dictionary containing input parameters.
  125. overall_ocr_res (OCRResult): Overall OCR result obtained after running the OCR pipeline.
  126. The overall OCR result with convert_points_to_boxes information.
  127. layout_det_res (DetResult): The layout detection result.
  128. Returns:
  129. bool: True if all required models are initialized according to input parameters, False otherwise.
  130. """
  131. if model_settings["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  132. logging.error(
  133. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  134. )
  135. return False
  136. if model_settings["use_layout_detection"]:
  137. if layout_det_res is not None:
  138. logging.error(
  139. "The layout detection model has already been initialized, please set use_layout_detection=False"
  140. )
  141. return False
  142. if not self.use_layout_detection:
  143. logging.error(
  144. "Set use_layout_detection, but the models for layout detection are not initialized."
  145. )
  146. return False
  147. if model_settings["use_ocr_model"]:
  148. if overall_ocr_res is not None:
  149. logging.error(
  150. "The OCR models have already been initialized, please set use_ocr_model=False"
  151. )
  152. return False
  153. if not self.use_ocr_model:
  154. logging.error(
  155. "Set use_ocr_model, but the models for OCR are not initialized."
  156. )
  157. return False
  158. else:
  159. if overall_ocr_res is None:
  160. logging.error("Set use_ocr_model=False, but no OCR results were found.")
  161. return False
  162. return True
  163. def predict_doc_preprocessor_res(
  164. self, image_array: np.ndarray, input_params: dict
  165. ) -> Tuple[DocPreprocessorResult, np.ndarray]:
  166. """
  167. Preprocess the document image based on input parameters.
  168. Args:
  169. image_array (np.ndarray): The input image array.
  170. input_params (dict): Dictionary containing preprocessing parameters.
  171. Returns:
  172. tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
  173. result dictionary and the processed image array.
  174. """
  175. if input_params["use_doc_preprocessor"]:
  176. use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
  177. use_doc_unwarping = input_params["use_doc_unwarping"]
  178. doc_preprocessor_res = next(
  179. self.doc_preprocessor_pipeline(
  180. image_array,
  181. use_doc_orientation_classify=use_doc_orientation_classify,
  182. use_doc_unwarping=use_doc_unwarping,
  183. )
  184. )
  185. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  186. else:
  187. doc_preprocessor_res = {}
  188. doc_preprocessor_image = image_array
  189. return doc_preprocessor_res, doc_preprocessor_image
  190. def split_ocr_bboxes_by_table_cells(self, ori_img, cells_bboxes):
  191. """
  192. Splits OCR bounding boxes by table cells and retrieves text.
  193. Args:
  194. ori_img (ndarray): The original image from which text regions will be extracted.
  195. cells_bboxes (list or ndarray): Detected cell bounding boxes to extract text from.
  196. Returns:
  197. list: A list containing the recognized texts from each cell.
  198. """
  199. # Check if cells_bboxes is a list and convert it if not.
  200. if not isinstance(cells_bboxes, list):
  201. cells_bboxes = cells_bboxes.tolist()
  202. texts_list = [] # Initialize a list to store the recognized texts.
  203. # Process each bounding box provided in cells_bboxes.
  204. for i in range(len(cells_bboxes)):
  205. # Extract and round up the coordinates of the bounding box.
  206. x1, y1, x2, y2 = [math.ceil(k) for k in cells_bboxes[i]]
  207. # Perform OCR on the defined region of the image and get the recognized text.
  208. rec_te = next(self.general_ocr_pipeline(ori_img[y1:y2, x1:x2, :]))
  209. # Concatenate the texts and append them to the texts_list.
  210. texts_list.append(''.join(rec_te["rec_texts"]))
  211. # Return the list of recognized texts from each cell.
  212. return texts_list
  213. def predict_single_table_recognition_res(
  214. self,
  215. image_array: np.ndarray,
  216. overall_ocr_res: OCRResult,
  217. table_box: list,
  218. use_table_cells_ocr_results: bool = False,
  219. flag_find_nei_text: bool = True,
  220. cell_sort_by_y_projection: bool = False,
  221. ) -> SingleTableRecognitionResult:
  222. """
  223. Predict table recognition results from an image array, layout detection results, and OCR results.
  224. Args:
  225. image_array (np.ndarray): The input image represented as a numpy array.
  226. overall_ocr_res (OCRResult): Overall OCR result obtained after running the OCR pipeline.
  227. The overall OCR results containing text recognition information.
  228. table_box (list): The table box coordinates.
  229. use_table_cells_ocr_results (bool): whether to use OCR results with cells.
  230. flag_find_nei_text (bool): Whether to find neighboring text.
  231. cell_sort_by_y_projection (bool): Whether to sort the matched OCR boxes by y-projection.
  232. Returns:
  233. SingleTableRecognitionResult: single table recognition result.
  234. """
  235. table_structure_pred = next(self.table_structure_model(image_array))
  236. if use_table_cells_ocr_results == True:
  237. table_cells_result = list(map(lambda arr: arr.tolist(), table_structure_pred['bbox']))
  238. table_cells_result = [[rect[0], rect[1], rect[4], rect[5]] for rect in table_cells_result]
  239. cells_texts_list = self.split_ocr_bboxes_by_table_cells(image_array, table_cells_result)
  240. else:
  241. cells_texts_list = []
  242. single_table_recognition_res = get_table_recognition_res(
  243. table_box,
  244. table_structure_pred,
  245. overall_ocr_res,
  246. cells_texts_list,
  247. use_table_cells_ocr_results,
  248. cell_sort_by_y_projection=cell_sort_by_y_projection,
  249. )
  250. neighbor_text = ""
  251. if flag_find_nei_text:
  252. match_idx_list = get_neighbor_boxes_idx(
  253. overall_ocr_res["rec_boxes"], table_box
  254. )
  255. if len(match_idx_list) > 0:
  256. for idx in match_idx_list:
  257. neighbor_text += overall_ocr_res["rec_texts"][idx] + "; "
  258. single_table_recognition_res["neighbor_texts"] = neighbor_text
  259. return single_table_recognition_res
  260. def predict(
  261. self,
  262. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  263. use_doc_orientation_classify: Optional[bool] = None,
  264. use_doc_unwarping: Optional[bool] = None,
  265. use_layout_detection: Optional[bool] = None,
  266. use_ocr_model: Optional[bool] = None,
  267. overall_ocr_res: Optional[OCRResult] = None,
  268. layout_det_res: Optional[DetResult] = None,
  269. text_det_limit_side_len: Optional[int] = None,
  270. text_det_limit_type: Optional[str] = None,
  271. text_det_thresh: Optional[float] = None,
  272. text_det_box_thresh: Optional[float] = None,
  273. text_det_unclip_ratio: Optional[float] = None,
  274. text_rec_score_thresh: Optional[float] = None,
  275. use_table_cells_ocr_results: Optional[bool] = False,
  276. cell_sort_by_y_projection: Optional[bool] = None,
  277. **kwargs,
  278. ) -> TableRecognitionResult:
  279. """
  280. This function predicts the layout parsing result for the given input.
  281. Args:
  282. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): The input image(s) of pdf(s) to be processed.
  283. use_layout_detection (bool): Whether to use layout detection.
  284. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  285. use_doc_unwarping (bool): Whether to use document unwarping.
  286. overall_ocr_res (OCRResult): The overall OCR result with convert_points_to_boxes information.
  287. It will be used if it is not None and use_ocr_model is False.
  288. layout_det_res (DetResult): The layout detection result.
  289. It will be used if it is not None and use_layout_detection is False.
  290. use_table_cells_ocr_results (bool): whether to use OCR results with cells.
  291. cell_sort_by_y_projection (bool): Whether to sort the matched OCR boxes by y-projection.
  292. **kwargs: Additional keyword arguments.
  293. Returns:
  294. TableRecognitionResult: The predicted table recognition result.
  295. """
  296. model_settings = self.get_model_settings(
  297. use_doc_orientation_classify,
  298. use_doc_unwarping,
  299. use_layout_detection,
  300. use_ocr_model,
  301. )
  302. if cell_sort_by_y_projection is None:
  303. cell_sort_by_y_projection = False
  304. if not self.check_model_settings_valid(
  305. model_settings, overall_ocr_res, layout_det_res
  306. ):
  307. yield {"error": "the input params for model settings are invalid!"}
  308. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  309. image_array = self.img_reader(batch_data.instances)[0]
  310. if model_settings["use_doc_preprocessor"]:
  311. doc_preprocessor_res = next(
  312. self.doc_preprocessor_pipeline(
  313. image_array,
  314. use_doc_orientation_classify=use_doc_orientation_classify,
  315. use_doc_unwarping=use_doc_unwarping,
  316. )
  317. )
  318. else:
  319. doc_preprocessor_res = {"output_img": image_array}
  320. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  321. if model_settings["use_ocr_model"]:
  322. overall_ocr_res = next(
  323. self.general_ocr_pipeline(
  324. doc_preprocessor_image,
  325. text_det_limit_side_len=text_det_limit_side_len,
  326. text_det_limit_type=text_det_limit_type,
  327. text_det_thresh=text_det_thresh,
  328. text_det_box_thresh=text_det_box_thresh,
  329. text_det_unclip_ratio=text_det_unclip_ratio,
  330. text_rec_score_thresh=text_rec_score_thresh,
  331. )
  332. )
  333. table_res_list = []
  334. table_region_id = 1
  335. if not model_settings["use_layout_detection"] and layout_det_res is None:
  336. layout_det_res = {}
  337. img_height, img_width = doc_preprocessor_image.shape[:2]
  338. table_box = [0, 0, img_width - 1, img_height - 1]
  339. single_table_rec_res = self.predict_single_table_recognition_res(
  340. doc_preprocessor_image,
  341. overall_ocr_res,
  342. table_box,
  343. use_table_cells_ocr_results,
  344. flag_find_nei_text=False,
  345. cell_sort_by_y_projection=cell_sort_by_y_projection,
  346. )
  347. single_table_rec_res["table_region_id"] = table_region_id
  348. table_res_list.append(single_table_rec_res)
  349. table_region_id += 1
  350. else:
  351. if model_settings["use_layout_detection"]:
  352. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  353. for box_info in layout_det_res["boxes"]:
  354. if box_info["label"].lower() in ["table"]:
  355. crop_img_info = self._crop_by_boxes(image_array, [box_info])
  356. crop_img_info = crop_img_info[0]
  357. table_box = crop_img_info["box"]
  358. single_table_rec_res = (
  359. self.predict_single_table_recognition_res(
  360. crop_img_info["img"],
  361. overall_ocr_res,
  362. table_box,
  363. use_table_cells_ocr_results,
  364. cell_sort_by_y_projection=cell_sort_by_y_projection,
  365. )
  366. )
  367. single_table_rec_res["table_region_id"] = table_region_id
  368. table_res_list.append(single_table_rec_res)
  369. table_region_id += 1
  370. single_img_res = {
  371. "input_path": batch_data.input_paths[0],
  372. "page_index": batch_data.page_indexes[0],
  373. "doc_preprocessor_res": doc_preprocessor_res,
  374. "layout_det_res": layout_det_res,
  375. "overall_ocr_res": overall_ocr_res,
  376. "table_res_list": table_res_list,
  377. "model_settings": model_settings,
  378. }
  379. yield TableRecognitionResult(single_img_res)