pipeline_v2.py 36 KB

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