pipeline_v2.py 36 KB

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