pipeline_v2.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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, List, Tuple
  16. import numpy as np
  17. import math
  18. import cv2
  19. from sklearn.cluster import KMeans
  20. from ..base import BasePipeline
  21. from ..components import CropByBoxes
  22. from .utils import get_neighbor_boxes_idx
  23. from .table_recognition_post_processing_v2 import get_table_recognition_res
  24. from .result import SingleTableRecognitionResult, TableRecognitionResult
  25. from ....utils import logging
  26. from ...utils.pp_option import PaddlePredictorOption
  27. from ...common.reader import ReadImage
  28. from ...common.batch_sampler import ImageBatchSampler
  29. from ..ocr.result import OCRResult
  30. from ..doc_preprocessor.result import DocPreprocessorResult
  31. from ...models.object_detection.result import DetResult
  32. class TableRecognitionPipelineV2(BasePipeline):
  33. """Table Recognition Pipeline"""
  34. entities = ["table_recognition_v2"]
  35. def __init__(
  36. self,
  37. config: Dict,
  38. device: str = None,
  39. pp_option: PaddlePredictorOption = None,
  40. use_hpip: bool = False,
  41. hpi_params: Optional[Dict[str, Any]] = None,
  42. ) -> None:
  43. """Initializes the layout parsing pipeline.
  44. Args:
  45. config (Dict): Configuration dictionary containing various settings.
  46. device (str, optional): Device to run the predictions on. Defaults to None.
  47. pp_option (PaddlePredictorOption, optional): PaddlePredictor options. Defaults to None.
  48. use_hpip (bool, optional): Whether to use high-performance inference (hpip) for prediction. Defaults to False.
  49. hpi_params (Optional[Dict[str, Any]], optional): HPIP parameters. Defaults to None.
  50. """
  51. super().__init__(
  52. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  53. )
  54. self.use_doc_preprocessor = config.get("use_doc_preprocessor", True)
  55. if self.use_doc_preprocessor:
  56. doc_preprocessor_config = config.get("SubPipelines", {}).get(
  57. "DocPreprocessor",
  58. {
  59. "pipeline_config_error": "config error for doc_preprocessor_pipeline!"
  60. },
  61. )
  62. self.doc_preprocessor_pipeline = self.create_pipeline(
  63. doc_preprocessor_config
  64. )
  65. self.use_layout_detection = config.get("use_layout_detection", True)
  66. if self.use_layout_detection:
  67. layout_det_config = config.get("SubModules", {}).get(
  68. "LayoutDetection",
  69. {"model_config_error": "config error for layout_det_model!"},
  70. )
  71. self.layout_det_model = self.create_model(layout_det_config)
  72. table_cls_config = config.get("SubModules", {}).get(
  73. "TableClassification",
  74. {"model_config_error": "config error for table_classification_model!"},
  75. )
  76. self.table_cls_model = self.create_model(table_cls_config)
  77. wired_table_rec_config = config.get("SubModules", {}).get(
  78. "WiredTableStructureRecognition",
  79. {"model_config_error": "config error for wired_table_structure_model!"},
  80. )
  81. self.wired_table_rec_model = self.create_model(wired_table_rec_config)
  82. wireless_table_rec_config = config.get("SubModules", {}).get(
  83. "WirelessTableStructureRecognition",
  84. {"model_config_error": "config error for wireless_table_structure_model!"},
  85. )
  86. self.wireless_table_rec_model = self.create_model(wireless_table_rec_config)
  87. wired_table_cells_det_config = config.get("SubModules", {}).get(
  88. "WiredTableCellsDetection",
  89. {
  90. "model_config_error": "config error for wired_table_cells_detection_model!"
  91. },
  92. )
  93. self.wired_table_cells_detection_model = self.create_model(
  94. wired_table_cells_det_config
  95. )
  96. wireless_table_cells_det_config = config.get("SubModules", {}).get(
  97. "WirelessTableCellsDetection",
  98. {
  99. "model_config_error": "config error for wireless_table_cells_detection_model!"
  100. },
  101. )
  102. self.wireless_table_cells_detection_model = self.create_model(
  103. wireless_table_cells_det_config
  104. )
  105. self.use_ocr_model = config.get("use_ocr_model", True)
  106. if self.use_ocr_model:
  107. general_ocr_config = config.get("SubPipelines", {}).get(
  108. "GeneralOCR",
  109. {"pipeline_config_error": "config error for general_ocr_pipeline!"},
  110. )
  111. self.general_ocr_pipeline = self.create_pipeline(general_ocr_config)
  112. self._crop_by_boxes = CropByBoxes()
  113. self.batch_sampler = ImageBatchSampler(batch_size=1)
  114. self.img_reader = ReadImage(format="BGR")
  115. def get_model_settings(
  116. self,
  117. use_doc_orientation_classify: Optional[bool],
  118. use_doc_unwarping: Optional[bool],
  119. use_layout_detection: Optional[bool],
  120. use_ocr_model: Optional[bool],
  121. ) -> dict:
  122. """
  123. Get the model settings based on the provided parameters or default values.
  124. Args:
  125. use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
  126. use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
  127. use_layout_detection (Optional[bool]): Whether to use layout detection.
  128. use_ocr_model (Optional[bool]): Whether to use OCR model.
  129. Returns:
  130. dict: A dictionary containing the model settings.
  131. """
  132. if use_doc_orientation_classify is None and use_doc_unwarping is None:
  133. use_doc_preprocessor = self.use_doc_preprocessor
  134. else:
  135. if use_doc_orientation_classify is True or use_doc_unwarping is True:
  136. use_doc_preprocessor = True
  137. else:
  138. use_doc_preprocessor = False
  139. if use_layout_detection is None:
  140. use_layout_detection = self.use_layout_detection
  141. if use_ocr_model is None:
  142. use_ocr_model = self.use_ocr_model
  143. return dict(
  144. use_doc_preprocessor=use_doc_preprocessor,
  145. use_layout_detection=use_layout_detection,
  146. use_ocr_model=use_ocr_model,
  147. )
  148. def check_model_settings_valid(
  149. self,
  150. model_settings: Dict,
  151. overall_ocr_res: OCRResult,
  152. layout_det_res: DetResult,
  153. ) -> bool:
  154. """
  155. Check if the input parameters are valid based on the initialized models.
  156. Args:
  157. model_settings (Dict): A dictionary containing input parameters.
  158. overall_ocr_res (OCRResult): Overall OCR result obtained after running the OCR pipeline.
  159. The overall OCR result with convert_points_to_boxes information.
  160. layout_det_res (DetResult): The layout detection result.
  161. Returns:
  162. bool: True if all required models are initialized according to input parameters, False otherwise.
  163. """
  164. if model_settings["use_doc_preprocessor"] and not self.use_doc_preprocessor:
  165. logging.error(
  166. "Set use_doc_preprocessor, but the models for doc preprocessor are not initialized."
  167. )
  168. return False
  169. if model_settings["use_layout_detection"]:
  170. if layout_det_res is not None:
  171. logging.error(
  172. "The layout detection model has already been initialized, please set use_layout_detection=False"
  173. )
  174. return False
  175. if not self.use_layout_detection:
  176. logging.error(
  177. "Set use_layout_detection, but the models for layout detection are not initialized."
  178. )
  179. return False
  180. if model_settings["use_ocr_model"]:
  181. if overall_ocr_res is not None:
  182. logging.error(
  183. "The OCR models have already been initialized, please set use_ocr_model=False"
  184. )
  185. return False
  186. if not self.use_ocr_model:
  187. logging.error(
  188. "Set use_ocr_model, but the models for OCR are not initialized."
  189. )
  190. return False
  191. else:
  192. if overall_ocr_res is None:
  193. logging.error("Set use_ocr_model=False, but no OCR results were found.")
  194. return False
  195. return True
  196. def predict_doc_preprocessor_res(
  197. self, image_array: np.ndarray, input_params: dict
  198. ) -> Tuple[DocPreprocessorResult, np.ndarray]:
  199. """
  200. Preprocess the document image based on input parameters.
  201. Args:
  202. image_array (np.ndarray): The input image array.
  203. input_params (dict): Dictionary containing preprocessing parameters.
  204. Returns:
  205. tuple[DocPreprocessorResult, np.ndarray]: A tuple containing the preprocessing
  206. result dictionary and the processed image array.
  207. """
  208. if input_params["use_doc_preprocessor"]:
  209. use_doc_orientation_classify = input_params["use_doc_orientation_classify"]
  210. use_doc_unwarping = input_params["use_doc_unwarping"]
  211. doc_preprocessor_res = next(
  212. self.doc_preprocessor_pipeline(
  213. image_array,
  214. use_doc_orientation_classify=use_doc_orientation_classify,
  215. use_doc_unwarping=use_doc_unwarping,
  216. )
  217. )
  218. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  219. else:
  220. doc_preprocessor_res = {}
  221. doc_preprocessor_image = image_array
  222. return doc_preprocessor_res, doc_preprocessor_image
  223. def extract_results(self, pred, task):
  224. if task == "cls":
  225. return pred["label_names"][np.argmax(pred["scores"])]
  226. elif task == "det":
  227. threshold = 0.0
  228. result = []
  229. cell_score = []
  230. if "boxes" in pred and isinstance(pred["boxes"], list):
  231. for box in pred["boxes"]:
  232. if isinstance(box, dict) and "score" in box and "coordinate" in box:
  233. score = box["score"]
  234. coordinate = box["coordinate"]
  235. if isinstance(score, float) and score > threshold:
  236. result.append(coordinate)
  237. cell_score.append(score)
  238. return result, cell_score
  239. elif task == "table_stru":
  240. return pred["structure"]
  241. else:
  242. return None
  243. def cells_det_results_nms(self, cells_det_results, cells_det_scores, cells_det_threshold=0.3):
  244. """
  245. Apply Non-Maximum Suppression (NMS) on detection results to remove redundant overlapping bounding boxes.
  246. Args:
  247. cells_det_results (list): List of bounding boxes, each box is in format [x1, y1, x2, y2].
  248. cells_det_scores (list): List of confidence scores corresponding to the bounding boxes.
  249. cells_det_threshold (float): IoU threshold for suppression. Boxes with IoU greater than this threshold
  250. will be suppressed. Default is 0.5.
  251. Returns:
  252. Tuple[list, list]: A tuple containing the list of bounding boxes and confidence scores after NMS,
  253. while maintaining one-to-one correspondence.
  254. """
  255. # Convert lists to numpy arrays for efficient computation
  256. boxes = np.array(cells_det_results)
  257. scores = np.array(cells_det_scores)
  258. # Initialize list for picked indices
  259. picked_indices = []
  260. # Get coordinates of bounding boxes
  261. x1 = boxes[:, 0]
  262. y1 = boxes[:, 1]
  263. x2 = boxes[:, 2]
  264. y2 = boxes[:, 3]
  265. # Compute the area of the bounding boxes
  266. areas = (x2 - x1) * (y2 - y1)
  267. # Sort the bounding boxes by the confidence scores in descending order
  268. order = scores.argsort()[::-1]
  269. # Process the boxes
  270. while order.size > 0:
  271. # Index of the current highest score box
  272. i = order[0]
  273. picked_indices.append(i)
  274. # Compute IoU between the highest score box and the rest
  275. xx1 = np.maximum(x1[i], x1[order[1:]])
  276. yy1 = np.maximum(y1[i], y1[order[1:]])
  277. xx2 = np.minimum(x2[i], x2[order[1:]])
  278. yy2 = np.minimum(y2[i], y2[order[1:]])
  279. # Compute the width and height of the overlapping area
  280. w = np.maximum(0.0, xx2 - xx1)
  281. h = np.maximum(0.0, yy2 - yy1)
  282. # Compute the ratio of overlap (IoU)
  283. inter = w * h
  284. ovr = inter / (areas[i] + areas[order[1:]] - inter)
  285. # Indices of boxes with IoU less than threshold
  286. inds = np.where(ovr <= cells_det_threshold)[0]
  287. # Update order, only keep boxes with IoU less than threshold
  288. order = order[inds + 1] # inds shifted by 1 because order[0] is the current box
  289. # Select the boxes and scores based on picked indices
  290. final_boxes = boxes[picked_indices].tolist()
  291. final_scores = scores[picked_indices].tolist()
  292. return final_boxes, final_scores
  293. def get_region_ocr_det_boxes(self, ocr_det_boxes, table_box):
  294. """Adjust the coordinates of ocr_det_boxes that are fully inside table_box relative to table_box.
  295. Args:
  296. ocr_det_boxes (list of list): List of bounding boxes [x1, y1, x2, y2] in the original image.
  297. table_box (list): Bounding box [x1, y1, x2, y2] of the target region in the original image.
  298. Returns:
  299. list of list: List of adjusted bounding boxes relative to table_box, for boxes fully inside table_box.
  300. """
  301. tol=0
  302. # Extract coordinates from table_box
  303. x_min_t, y_min_t, x_max_t, y_max_t = table_box
  304. adjusted_boxes = []
  305. for box in ocr_det_boxes:
  306. x_min_b, y_min_b, x_max_b, y_max_b = box
  307. # Check if the box is fully inside table_box
  308. if (x_min_b+tol >= x_min_t and y_min_b+tol >= y_min_t and
  309. x_max_b-tol <= x_max_t and y_max_b-tol <= y_max_t):
  310. # Adjust the coordinates to be relative to table_box
  311. adjusted_box = [
  312. x_min_b - x_min_t, # Adjust x1
  313. y_min_b - y_min_t, # Adjust y1
  314. x_max_b - x_min_t, # Adjust x2
  315. y_max_b - y_min_t # Adjust y2
  316. ]
  317. adjusted_boxes.append(adjusted_box)
  318. # Discard boxes not fully inside table_box
  319. return adjusted_boxes
  320. def cells_det_results_reprocessing(self, cells_det_results, cells_det_scores, ocr_det_results, html_pred_boxes_nums):
  321. """
  322. Process and filter cells_det_results based on ocr_det_results and html_pred_boxes_nums.
  323. Args:
  324. cells_det_results (List[List[float]]): List of detected cell rectangles [[x1, y1, x2, y2], ...].
  325. cells_det_scores (List[float]): List of confidence scores for each rectangle in cells_det_results.
  326. ocr_det_results (List[List[float]]): List of OCR detected rectangles [[x1, y1, x2, y2], ...].
  327. html_pred_boxes_nums (int): The desired number of rectangles in the final output.
  328. Returns:
  329. List[List[float]]: The processed list of rectangles.
  330. """
  331. # Function to compute IoU between two rectangles
  332. def compute_iou(box1, box2):
  333. """
  334. Compute the Intersection over Union (IoU) between two rectangles.
  335. Args:
  336. box1 (array-like): [x1, y1, x2, y2] of the first rectangle.
  337. box2 (array-like): [x1, y1, x2, y2] of the second rectangle.
  338. Returns:
  339. float: The IoU between the two rectangles.
  340. """
  341. # Determine the coordinates of the intersection rectangle
  342. x_left = max(box1[0], box2[0])
  343. y_top = max(box1[1], box2[1])
  344. x_right = min(box1[2], box2[2])
  345. y_bottom = min(box1[3], box2[3])
  346. if x_right <= x_left or y_bottom <= y_top:
  347. return 0.0
  348. # Calculate the area of intersection rectangle
  349. intersection_area = (x_right - x_left) * (y_bottom - y_top)
  350. # Calculate the area of both rectangles
  351. box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
  352. box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
  353. # Calculate the IoU
  354. iou = intersection_area / float(box1_area)
  355. return iou
  356. # Function to combine rectangles into N rectangles
  357. def combine_rectangles(rectangles, N):
  358. """
  359. Combine rectangles into N rectangles based on geometric proximity.
  360. Args:
  361. rectangles (list of list of int): A list of rectangles, each represented by [x1, y1, x2, y2].
  362. N (int): The desired number of combined rectangles.
  363. Returns:
  364. list of list of int: A list of N combined rectangles.
  365. """
  366. # Number of input rectangles
  367. num_rects = len(rectangles)
  368. # If N is greater than or equal to the number of rectangles, return the original rectangles
  369. if N >= num_rects:
  370. return rectangles
  371. # Compute the center points of the rectangles
  372. centers = np.array([
  373. [
  374. (rect[0] + rect[2]) / 2, # Center x-coordinate
  375. (rect[1] + rect[3]) / 2 # Center y-coordinate
  376. ]
  377. for rect in rectangles
  378. ])
  379. # Perform KMeans clustering on the center points to group them into N clusters
  380. kmeans = KMeans(n_clusters=N, random_state=0, n_init='auto')
  381. labels = kmeans.fit_predict(centers)
  382. # Initialize a list to store the combined rectangles
  383. combined_rectangles = []
  384. # For each cluster, compute the minimal bounding rectangle that covers all rectangles in the cluster
  385. for i in range(N):
  386. # Get the indices of rectangles that belong to cluster i
  387. indices = np.where(labels == i)[0]
  388. if len(indices) == 0:
  389. # If no rectangles in this cluster, skip it
  390. continue
  391. # Extract the rectangles in cluster i
  392. cluster_rects = np.array([rectangles[idx] for idx in indices])
  393. # Compute the minimal x1, y1 (top-left corner) and maximal x2, y2 (bottom-right corner)
  394. x1_min = np.min(cluster_rects[:, 0])
  395. y1_min = np.min(cluster_rects[:, 1])
  396. x2_max = np.max(cluster_rects[:, 2])
  397. y2_max = np.max(cluster_rects[:, 3])
  398. # Append the combined rectangle to the list
  399. combined_rectangles.append([x1_min, y1_min, x2_max, y2_max])
  400. return combined_rectangles
  401. # Ensure that the inputs are numpy arrays for efficient computation
  402. cells_det_results = np.array(cells_det_results)
  403. cells_det_scores = np.array(cells_det_scores)
  404. ocr_det_results = np.array(ocr_det_results)
  405. more_cells_flag = False
  406. if len(cells_det_results) == html_pred_boxes_nums:
  407. return cells_det_results
  408. # Step 1: If cells_det_results has more rectangles than html_pred_boxes_nums
  409. elif len(cells_det_results) > html_pred_boxes_nums:
  410. more_cells_flag = True
  411. # Select the indices of the top html_pred_boxes_nums scores
  412. top_indices = np.argsort(-cells_det_scores)[:html_pred_boxes_nums]
  413. # Adjust the corresponding rectangles
  414. cells_det_results = cells_det_results[top_indices].tolist()
  415. # Threshold for IoU
  416. iou_threshold = 0.6
  417. # List to store ocr_miss_boxes
  418. ocr_miss_boxes = []
  419. # For each rectangle in ocr_det_results
  420. for ocr_rect in ocr_det_results:
  421. merge_ocr_box_iou = []
  422. # Flag to indicate if ocr_rect has IoU >= threshold with any cell_rect
  423. has_large_iou = False
  424. # For each rectangle in cells_det_results
  425. for cell_rect in cells_det_results:
  426. # Compute IoU
  427. iou = compute_iou(ocr_rect, cell_rect)
  428. if iou > 0:
  429. merge_ocr_box_iou.append(iou)
  430. if (iou>=iou_threshold) or (sum(merge_ocr_box_iou)>=iou_threshold):
  431. has_large_iou = True
  432. break
  433. if not has_large_iou:
  434. ocr_miss_boxes.append(ocr_rect)
  435. # If no ocr_miss_boxes, return cells_det_results
  436. if len(ocr_miss_boxes) == 0:
  437. final_results = cells_det_results if more_cells_flag==True else cells_det_results.tolist()
  438. else:
  439. if more_cells_flag == True:
  440. final_results = combine_rectangles(cells_det_results+ocr_miss_boxes, html_pred_boxes_nums)
  441. else:
  442. # Need to combine ocr_miss_boxes into N rectangles
  443. N = html_pred_boxes_nums - len(cells_det_results)
  444. # Combine ocr_miss_boxes into N rectangles
  445. ocr_supp_boxes = combine_rectangles(ocr_miss_boxes, N)
  446. # Combine cells_det_results and ocr_supp_boxes
  447. final_results = np.concatenate((cells_det_results, ocr_supp_boxes), axis=0).tolist()
  448. if len(final_results) <= 0.6*html_pred_boxes_nums:
  449. final_results = combine_rectangles(ocr_det_results, html_pred_boxes_nums)
  450. return final_results
  451. def split_ocr_bboxes_by_table_cells(self, ori_img, cells_bboxes):
  452. """
  453. Splits OCR bounding boxes by table cells and retrieves text.
  454. Args:
  455. ori_img (ndarray): The original image from which text regions will be extracted.
  456. cells_bboxes (list or ndarray): Detected cell bounding boxes to extract text from.
  457. Returns:
  458. list: A list containing the recognized texts from each cell.
  459. """
  460. # Check if cells_bboxes is a list and convert it if not.
  461. if not isinstance(cells_bboxes, list):
  462. cells_bboxes = cells_bboxes.tolist()
  463. texts_list = [] # Initialize a list to store the recognized texts.
  464. # Process each bounding box provided in cells_bboxes.
  465. for i in range(len(cells_bboxes)):
  466. # Extract and round up the coordinates of the bounding box.
  467. x1, y1, x2, y2 = [math.ceil(k) for k in cells_bboxes[i]]
  468. # Perform OCR on the defined region of the image and get the recognized text.
  469. rec_te = next(self.general_ocr_pipeline(ori_img[y1:y2, x1:x2, :]))
  470. # Concatenate the texts and append them to the texts_list.
  471. texts_list.append(''.join(rec_te["rec_texts"]))
  472. # Return the list of recognized texts from each cell.
  473. return texts_list
  474. def predict_single_table_recognition_res(
  475. self,
  476. image_array: np.ndarray,
  477. overall_ocr_res: OCRResult,
  478. table_box: list,
  479. use_table_cells_ocr_results: bool = False,
  480. flag_find_nei_text: bool = True,
  481. ) -> SingleTableRecognitionResult:
  482. """
  483. Predict table recognition results from an image array, layout detection results, and OCR results.
  484. Args:
  485. image_array (np.ndarray): The input image represented as a numpy array.
  486. overall_ocr_res (OCRResult): Overall OCR result obtained after running the OCR pipeline.
  487. The overall OCR results containing text recognition information.
  488. table_box (list): The table box coordinates.
  489. flag_find_nei_text (bool): Whether to find neighboring text.
  490. Returns:
  491. SingleTableRecognitionResult: single table recognition result.
  492. """
  493. table_cls_pred = next(self.table_cls_model(image_array))
  494. table_cls_result = self.extract_results(table_cls_pred, "cls")
  495. if table_cls_result == "wired_table":
  496. table_structure_pred = next(self.wired_table_rec_model(image_array))
  497. table_cells_pred = next(
  498. self.wired_table_cells_detection_model(image_array, threshold=0.3)
  499. ) # Setting the threshold to 0.3 can improve the accuracy of table cells detection.
  500. # If you really want more or fewer table cells detection boxes, the threshold can be adjusted.
  501. elif table_cls_result == "wireless_table":
  502. table_structure_pred = next(self.wireless_table_rec_model(image_array))
  503. table_cells_pred = next(
  504. self.wireless_table_cells_detection_model(image_array, threshold=0.3)
  505. ) # Setting the threshold to 0.3 can improve the accuracy of table cells detection.
  506. # If you really want more or fewer table cells detection boxes, the threshold can be adjusted.
  507. table_structure_result = self.extract_results(table_structure_pred, "table_stru")
  508. table_cells_result, table_cells_score = self.extract_results(table_cells_pred, "det")
  509. table_cells_result, table_cells_score = self.cells_det_results_nms(table_cells_result, table_cells_score)
  510. ocr_det_boxes = self.get_region_ocr_det_boxes(overall_ocr_res["rec_boxes"].tolist(), table_box)
  511. table_cells_result = self.cells_det_results_reprocessing(
  512. table_cells_result, table_cells_score, ocr_det_boxes, len(table_structure_pred['bbox'])
  513. )
  514. if use_table_cells_ocr_results == True:
  515. cells_texts_list = self.split_ocr_bboxes_by_table_cells(image_array, table_cells_result)
  516. else:
  517. cells_texts_list = []
  518. single_table_recognition_res = get_table_recognition_res(
  519. table_box, table_structure_result, table_cells_result, overall_ocr_res, cells_texts_list, use_table_cells_ocr_results
  520. )
  521. neighbor_text = ""
  522. if flag_find_nei_text:
  523. match_idx_list = get_neighbor_boxes_idx(
  524. overall_ocr_res["rec_boxes"], table_box
  525. )
  526. if len(match_idx_list) > 0:
  527. for idx in match_idx_list:
  528. neighbor_text += overall_ocr_res["rec_texts"][idx] + "; "
  529. single_table_recognition_res["neighbor_texts"] = neighbor_text
  530. return single_table_recognition_res
  531. def predict(
  532. self,
  533. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  534. use_doc_orientation_classify: Optional[bool] = None,
  535. use_doc_unwarping: Optional[bool] = None,
  536. use_layout_detection: Optional[bool] = None,
  537. use_ocr_model: Optional[bool] = None,
  538. overall_ocr_res: Optional[OCRResult] = None,
  539. layout_det_res: Optional[DetResult] = None,
  540. text_det_limit_side_len: Optional[int] = None,
  541. text_det_limit_type: Optional[str] = None,
  542. text_det_thresh: Optional[float] = None,
  543. text_det_box_thresh: Optional[float] = None,
  544. text_det_unclip_ratio: Optional[float] = None,
  545. text_rec_score_thresh: Optional[float] = None,
  546. use_table_cells_ocr_results: Optional[bool] = False,
  547. **kwargs,
  548. ) -> TableRecognitionResult:
  549. """
  550. This function predicts the layout parsing result for the given input.
  551. Args:
  552. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): The input image(s) of pdf(s) to be processed.
  553. use_layout_detection (bool): Whether to use layout detection.
  554. use_doc_orientation_classify (bool): Whether to use document orientation classification.
  555. use_doc_unwarping (bool): Whether to use document unwarping.
  556. overall_ocr_res (OCRResult): The overall OCR result with convert_points_to_boxes information.
  557. It will be used if it is not None and use_ocr_model is False.
  558. layout_det_res (DetResult): The layout detection result.
  559. It will be used if it is not None and use_layout_detection is False.
  560. **kwargs: Additional keyword arguments.
  561. Returns:
  562. TableRecognitionResult: The predicted table recognition result.
  563. """
  564. model_settings = self.get_model_settings(
  565. use_doc_orientation_classify,
  566. use_doc_unwarping,
  567. use_layout_detection,
  568. use_ocr_model,
  569. )
  570. if not self.check_model_settings_valid(
  571. model_settings, overall_ocr_res, layout_det_res
  572. ):
  573. yield {"error": "the input params for model settings are invalid!"}
  574. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  575. image_array = self.img_reader(batch_data.instances)[0]
  576. if model_settings["use_doc_preprocessor"]:
  577. doc_preprocessor_res = next(
  578. self.doc_preprocessor_pipeline(
  579. image_array,
  580. use_doc_orientation_classify=use_doc_orientation_classify,
  581. use_doc_unwarping=use_doc_unwarping,
  582. )
  583. )
  584. else:
  585. doc_preprocessor_res = {"output_img": image_array}
  586. doc_preprocessor_image = doc_preprocessor_res["output_img"]
  587. if model_settings["use_ocr_model"]:
  588. overall_ocr_res = next(
  589. self.general_ocr_pipeline(
  590. doc_preprocessor_image,
  591. text_det_limit_side_len=text_det_limit_side_len,
  592. text_det_limit_type=text_det_limit_type,
  593. text_det_thresh=text_det_thresh,
  594. text_det_box_thresh=text_det_box_thresh,
  595. text_det_unclip_ratio=text_det_unclip_ratio,
  596. text_rec_score_thresh=text_rec_score_thresh,
  597. )
  598. )
  599. table_res_list = []
  600. table_region_id = 1
  601. if not model_settings["use_layout_detection"] and layout_det_res is None:
  602. layout_det_res = {}
  603. img_height, img_width = doc_preprocessor_image.shape[:2]
  604. table_box = [0, 0, img_width - 1, img_height - 1]
  605. single_table_rec_res = self.predict_single_table_recognition_res(
  606. doc_preprocessor_image,
  607. overall_ocr_res,
  608. table_box,
  609. use_table_cells_ocr_results,
  610. flag_find_nei_text=False,
  611. )
  612. single_table_rec_res["table_region_id"] = table_region_id
  613. table_res_list.append(single_table_rec_res)
  614. table_region_id += 1
  615. else:
  616. if model_settings["use_layout_detection"]:
  617. layout_det_res = next(self.layout_det_model(doc_preprocessor_image))
  618. for box_info in layout_det_res["boxes"]:
  619. if box_info["label"].lower() in ["table"]:
  620. crop_img_info = self._crop_by_boxes(image_array, [box_info])
  621. crop_img_info = crop_img_info[0]
  622. table_box = crop_img_info["box"]
  623. single_table_rec_res = (
  624. self.predict_single_table_recognition_res(
  625. crop_img_info["img"], overall_ocr_res, table_box, use_table_cells_ocr_results
  626. )
  627. )
  628. single_table_rec_res["table_region_id"] = table_region_id
  629. table_res_list.append(single_table_rec_res)
  630. table_region_id += 1
  631. single_img_res = {
  632. "input_path": batch_data.input_paths[0],
  633. "page_index": batch_data.page_indexes[0],
  634. "doc_preprocessor_res": doc_preprocessor_res,
  635. "layout_det_res": layout_det_res,
  636. "overall_ocr_res": overall_ocr_res,
  637. "table_res_list": table_res_list,
  638. "model_settings": model_settings,
  639. }
  640. yield TableRecognitionResult(single_img_res)