table_recognition_post_processing_v2.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. import numpy as np
  16. from ..components import convert_points_to_boxes
  17. from ..layout_parsing.utils import get_sub_regions_ocr_res
  18. from ..ocr.result import OCRResult
  19. from .result import SingleTableRecognitionResult
  20. def get_ori_image_coordinate(x: int, y: int, box_list: list) -> list:
  21. """
  22. get the original coordinate from Cropped image to Original image.
  23. Args:
  24. x (int): x coordinate of cropped image
  25. y (int): y coordinate of cropped image
  26. box_list (list): list of table bounding boxes, eg. [[x1, y1, x2, y2, x3, y3, x4, y4]]
  27. Returns:
  28. list: list of original coordinates, eg. [[x1, y1, x2, y2, x3, y3, x4, y4]]
  29. """
  30. if not box_list:
  31. return box_list
  32. offset = np.array([x, y] * 4)
  33. box_list = np.array(box_list)
  34. if box_list.shape[-1] == 2:
  35. offset = offset.reshape(4, 2)
  36. ori_box_list = offset + box_list
  37. return ori_box_list
  38. def convert_table_structure_pred_bbox(
  39. cell_points_list: list, crop_start_point: list, img_shape: tuple
  40. ) -> None:
  41. """
  42. Convert the predicted table structure bounding boxes to the original image coordinate system.
  43. Args:
  44. cell_points_list (list): Bounding boxes ('bbox').
  45. crop_start_point (list): A list of two integers representing the starting point (x, y) of the cropped image region.
  46. img_shape (tuple): A tuple of two integers representing the shape (height, width) of the original image.
  47. Returns:
  48. cell_points_list (list): Bounding boxes ('bbox').
  49. """
  50. ori_cell_points_list = get_ori_image_coordinate(
  51. crop_start_point[0], crop_start_point[1], cell_points_list
  52. )
  53. ori_cell_points_list = np.reshape(ori_cell_points_list, (-1, 4, 2))
  54. cell_box_list = convert_points_to_boxes(ori_cell_points_list)
  55. img_height, img_width = img_shape
  56. cell_box_list = np.clip(
  57. cell_box_list, 0, [img_width, img_height, img_width, img_height]
  58. )
  59. return cell_box_list
  60. def distance(box_1: list, box_2: list) -> float:
  61. """
  62. compute the distance between two boxes
  63. Args:
  64. box_1 (list): first rectangle box,eg.(x1, y1, x2, y2)
  65. box_2 (list): second rectangle box,eg.(x1, y1, x2, y2)
  66. Returns:
  67. float: the distance between two boxes
  68. """
  69. x1, y1, x2, y2 = box_1
  70. x3, y3, x4, y4 = box_2
  71. center1_x = (x1 + x2) / 2
  72. center1_y = (y1 + y2) / 2
  73. center2_x = (x3 + x4) / 2
  74. center2_y = (y3 + y4) / 2
  75. dis = math.sqrt((center2_x - center1_x) ** 2 + (center2_y - center1_y) ** 2)
  76. dis_2 = abs(x3 - x1) + abs(y3 - y1)
  77. dis_3 = abs(x4 - x2) + abs(y4 - y2)
  78. return dis + min(dis_2, dis_3)
  79. def compute_iou(rec1: list, rec2: list) -> float:
  80. """
  81. computing IoU
  82. Args:
  83. rec1 (list): (x1, y1, x2, y2)
  84. rec2 (list): (x1, y1, x2, y2)
  85. Returns:
  86. float: Intersection over Union
  87. """
  88. # computing area of each rectangles
  89. S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
  90. S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
  91. # computing the sum_area
  92. sum_area = S_rec1 + S_rec2
  93. # find the each edge of intersect rectangle
  94. left_line = max(rec1[0], rec2[0])
  95. right_line = min(rec1[2], rec2[2])
  96. top_line = max(rec1[1], rec2[1])
  97. bottom_line = min(rec1[3], rec2[3])
  98. # judge if there is an intersect
  99. if left_line >= right_line or top_line >= bottom_line:
  100. return 0.0
  101. else:
  102. intersect = (right_line - left_line) * (bottom_line - top_line)
  103. return (intersect / (sum_area - intersect)) * 1.0
  104. def compute_inter(rec1, rec2):
  105. """
  106. computing intersection over rec2_area
  107. Args:
  108. rec1 (list): (x1, y1, x2, y2)
  109. rec2 (list): (x1, y1, x2, y2)
  110. Returns:
  111. float: Intersection over rec2_area
  112. """
  113. x1_1, y1_1, x2_1, y2_1 = map(float, rec1)
  114. x1_2, y1_2, x2_2, y2_2 = map(float, rec2)
  115. x_left = max(x1_1, x1_2)
  116. y_top = max(y1_1, y1_2)
  117. x_right = min(x2_1, x2_2)
  118. y_bottom = min(y2_1, y2_2)
  119. inter_width = max(0, x_right - x_left)
  120. inter_height = max(0, y_bottom - y_top)
  121. inter_area = inter_width * inter_height
  122. rec2_area = (x2_2 - x1_2) * (y2_2 - y1_2)
  123. if rec2_area == 0:
  124. return 0
  125. iou = inter_area / rec2_area
  126. return iou
  127. def match_table_and_ocr(cell_box_list, ocr_dt_boxes, table_cells_flag, row_start_index):
  128. """
  129. match table and ocr
  130. Args:
  131. cell_box_list (list): bbox for table cell, 2 points, [left, top, right, bottom]
  132. ocr_dt_boxes (list): bbox for ocr, 2 points, [left, top, right, bottom]
  133. Returns:
  134. dict: matched dict, key is table index, value is ocr index
  135. """
  136. all_matched = []
  137. for k in range(len(table_cells_flag) - 1):
  138. matched = {}
  139. for i, table_box in enumerate(
  140. cell_box_list[table_cells_flag[k] : table_cells_flag[k + 1]]
  141. ):
  142. if len(table_box) == 8:
  143. table_box = [
  144. np.min(table_box[0::2]),
  145. np.min(table_box[1::2]),
  146. np.max(table_box[0::2]),
  147. np.max(table_box[1::2]),
  148. ]
  149. for j, ocr_box in enumerate(np.array(ocr_dt_boxes)):
  150. if compute_inter(table_box, ocr_box) > 0.7:
  151. if i not in matched.keys():
  152. matched[i] = [j]
  153. else:
  154. matched[i].append(j)
  155. real_len = max(matched.keys()) + 1 if len(matched) != 0 else 0
  156. if table_cells_flag[k + 1] < row_start_index[k + 1]:
  157. for s in range(row_start_index[k + 1] - table_cells_flag[k + 1]):
  158. matched[real_len + s] = []
  159. elif table_cells_flag[k + 1] > row_start_index[k + 1]:
  160. for s in range(table_cells_flag[k + 1] - row_start_index[k + 1]):
  161. matched[real_len - 1].append(matched[real_len + s])
  162. all_matched.append(matched)
  163. return all_matched
  164. def get_html_result(
  165. all_matched_index: dict, ocr_contents: dict, pred_structures: list, table_cells_flag
  166. ) -> str:
  167. """
  168. Generates HTML content based on the matched index, OCR contents, and predicted structures.
  169. Args:
  170. matched_index (dict): A dictionary containing matched indices.
  171. ocr_contents (dict): A dictionary of OCR contents.
  172. pred_structures (list): A list of predicted HTML structures.
  173. Returns:
  174. str: Generated HTML content as a string.
  175. """
  176. pred_html = []
  177. td_index = 0
  178. td_count = 0
  179. matched_list_index = 0
  180. head_structure = pred_structures[0:3]
  181. html = "".join(head_structure)
  182. table_structure = pred_structures[3:-3]
  183. for tag in table_structure:
  184. matched_index = all_matched_index[matched_list_index]
  185. if "</td>" in tag:
  186. if "<td></td>" == tag:
  187. pred_html.extend("<td>")
  188. if td_index in matched_index.keys():
  189. if len(matched_index[td_index]) == 0:
  190. continue
  191. b_with = False
  192. if (
  193. "<b>" in ocr_contents[matched_index[td_index][0]]
  194. and len(matched_index[td_index]) > 1
  195. ):
  196. b_with = True
  197. pred_html.extend("<b>")
  198. for i, td_index_index in enumerate(matched_index[td_index]):
  199. content = ocr_contents[td_index_index]
  200. if len(matched_index[td_index]) > 1:
  201. if len(content) == 0:
  202. continue
  203. if content[0] == " ":
  204. content = content[1:]
  205. if "<b>" in content:
  206. content = content[3:]
  207. if "</b>" in content:
  208. content = content[:-4]
  209. if len(content) == 0:
  210. continue
  211. if i != len(matched_index[td_index]) - 1 and " " != content[-1]:
  212. content += " "
  213. pred_html.extend(content)
  214. if b_with:
  215. pred_html.extend("</b>")
  216. if "<td></td>" == tag:
  217. pred_html.append("</td>")
  218. else:
  219. pred_html.append(tag)
  220. td_index += 1
  221. td_count += 1
  222. if (
  223. td_count >= table_cells_flag[matched_list_index + 1]
  224. and matched_list_index < len(all_matched_index) - 1
  225. ):
  226. matched_list_index += 1
  227. td_index = 0
  228. else:
  229. pred_html.append(tag)
  230. html += "".join(pred_html)
  231. end_structure = pred_structures[-3:]
  232. html += "".join(end_structure)
  233. return html
  234. def sort_table_cells_boxes(boxes):
  235. """
  236. Sort the input list of bounding boxes.
  237. Args:
  238. boxes (list of lists): The input list of bounding boxes, where each bounding box is formatted as [x1, y1, x2, y2].
  239. Returns:
  240. sorted_boxes (list of lists): The list of bounding boxes sorted.
  241. """
  242. boxes_sorted_by_y = sorted(boxes, key=lambda box: box[1])
  243. rows = []
  244. current_row = []
  245. current_y = None
  246. tolerance = 10
  247. for box in boxes_sorted_by_y:
  248. x1, y1, x2, y2 = box
  249. if current_y is None:
  250. current_row.append(box)
  251. current_y = y1
  252. else:
  253. if abs(y1 - current_y) <= tolerance:
  254. current_row.append(box)
  255. else:
  256. current_row.sort(key=lambda x: x[0])
  257. rows.append(current_row)
  258. current_row = [box]
  259. current_y = y1
  260. if current_row:
  261. current_row.sort(key=lambda x: x[0])
  262. rows.append(current_row)
  263. sorted_boxes = []
  264. flag = [0]
  265. for i in range(len(rows)):
  266. sorted_boxes.extend(rows[i])
  267. if i < len(rows):
  268. flag.append(flag[i] + len(rows[i]))
  269. return sorted_boxes, flag
  270. def convert_to_four_point_coordinates(boxes):
  271. """
  272. Convert bounding boxes from [x1, y1, x2, y2] format to
  273. [x1, y1, x2, y1, x2, y2, x1, y2] format.
  274. Parameters:
  275. - boxes: A list of bounding boxes, each defined as a list of integers
  276. in the format [x1, y1, x2, y2].
  277. Returns:
  278. - A list of bounding boxes, each converted to the format
  279. [x1, y1, x2, y1, x2, y2, x1, y2].
  280. """
  281. # Initialize an empty list to store the converted bounding boxes
  282. converted_boxes = []
  283. # Loop over each box in the input list
  284. for box in boxes:
  285. x1, y1, x2, y2 = box
  286. # Define the four corner points
  287. top_left = (x1, y1)
  288. top_right = (x2, y1)
  289. bottom_right = (x2, y2)
  290. bottom_left = (x1, y2)
  291. # Create a new list for the converted box
  292. converted_box = [
  293. top_left[0],
  294. top_left[1], # Top-left corner
  295. top_right[0],
  296. top_right[1], # Top-right corner
  297. bottom_right[0],
  298. bottom_right[1], # Bottom-right corner
  299. bottom_left[0],
  300. bottom_left[1], # Bottom-left corner
  301. ]
  302. # Append the converted box to the list
  303. converted_boxes.append(converted_box)
  304. return converted_boxes
  305. def find_row_start_index(html_list):
  306. """
  307. find the index of the first cell in each row
  308. Args:
  309. html_list (list): list for html results
  310. Returns:
  311. row_start_indices (list): list for the index of the first cell in each row
  312. """
  313. # Initialize an empty list to store the indices of row start positions
  314. row_start_indices = []
  315. # Variable to track the current index in the flattened HTML content
  316. current_index = 0
  317. # Flag to check if we are inside a table row
  318. inside_row = False
  319. # Iterate through the HTML tags
  320. for keyword in html_list:
  321. # If a new row starts, set the inside_row flag to True
  322. if keyword == "<tr>":
  323. inside_row = True
  324. # If we encounter a closing row tag, set the inside_row flag to False
  325. elif keyword == "</tr>":
  326. inside_row = False
  327. # If we encounter a cell and we are inside a row
  328. elif (keyword == "<td></td>" or keyword == "</td>") and inside_row:
  329. # Append the current index as the starting index of the row
  330. row_start_indices.append(current_index)
  331. # Set the flag to ensure we only record the first cell of the current row
  332. inside_row = False
  333. # Increment the current index if we encounter a cell regardless of being inside a row or not
  334. if keyword == "<td></td>" or keyword == "</td>":
  335. current_index += 1
  336. # Return the computed starting indices of each row
  337. return row_start_indices
  338. def map_and_get_max(table_cells_flag, row_start_index):
  339. """
  340. Retrieve table recognition result from cropped image info, table structure prediction, and overall OCR result.
  341. Args:
  342. table_cells_flag (list): List of the flags representing the end of each row of the table cells detection results.
  343. row_start_index (list): List of the flags representing the end of each row of the table structure predicted results.
  344. Returns:
  345. max_values: List of the process results.
  346. """
  347. max_values = []
  348. i = 0
  349. max_value = None
  350. for j in range(len(row_start_index)):
  351. while i < len(table_cells_flag) and table_cells_flag[i] <= row_start_index[j]:
  352. if max_value is None or table_cells_flag[i] > max_value:
  353. max_value = table_cells_flag[i]
  354. i += 1
  355. max_values.append(max_value if max_value is not None else row_start_index[j])
  356. return max_values
  357. def get_table_recognition_res(
  358. table_box: list,
  359. table_structure_result: list,
  360. table_cells_result: list,
  361. overall_ocr_res: OCRResult,
  362. table_ocr_pred: dict,
  363. cells_texts_list: list,
  364. use_table_cells_ocr_results: bool,
  365. use_table_cells_split_ocr: bool,
  366. ) -> SingleTableRecognitionResult:
  367. """
  368. Retrieve table recognition result from cropped image info, table structure prediction, and overall OCR result.
  369. Args:
  370. table_box (list): Information about the location of cropped image, including the bounding box.
  371. table_structure_result (list): Predicted table structure.
  372. table_cells_result (list): Predicted table cells.
  373. overall_ocr_res (OCRResult): Overall OCR result from the input image.
  374. table_ocr_pred (dict): Table OCR result from the input image.
  375. cells_texts_list (list): OCR results with cells.
  376. use_table_cells_ocr_results (bool): whether to use OCR results with cells.
  377. Returns:
  378. SingleTableRecognitionResult: An object containing the single table recognition result.
  379. """
  380. table_cells_result = convert_to_four_point_coordinates(table_cells_result)
  381. table_box = np.array([table_box])
  382. if not (use_table_cells_ocr_results == True and use_table_cells_split_ocr == True):
  383. table_ocr_pred = get_sub_regions_ocr_res(overall_ocr_res, table_box)
  384. crop_start_point = [table_box[0][0], table_box[0][1]]
  385. img_shape = overall_ocr_res["doc_preprocessor_res"]["output_img"].shape[0:2]
  386. if len(table_cells_result) == 0 or len(table_ocr_pred["rec_boxes"]) == 0:
  387. pred_html = " ".join(table_structure_result)
  388. if len(table_cells_result) != 0:
  389. table_cells_result = convert_table_structure_pred_bbox(
  390. table_cells_result, crop_start_point, img_shape
  391. )
  392. single_img_res = {
  393. "cell_box_list": table_cells_result,
  394. "table_ocr_pred": table_ocr_pred,
  395. "pred_html": pred_html,
  396. }
  397. return SingleTableRecognitionResult(single_img_res)
  398. table_cells_result = convert_table_structure_pred_bbox(
  399. table_cells_result, crop_start_point, img_shape
  400. )
  401. if use_table_cells_ocr_results == True and use_table_cells_split_ocr == False:
  402. ocr_dt_boxes = table_cells_result
  403. ocr_texts_res = cells_texts_list
  404. else:
  405. ocr_dt_boxes = table_ocr_pred["rec_boxes"]
  406. ocr_texts_res = table_ocr_pred["rec_texts"]
  407. table_cells_result, table_cells_flag = sort_table_cells_boxes(table_cells_result)
  408. row_start_index = find_row_start_index(table_structure_result)
  409. table_cells_flag = map_and_get_max(table_cells_flag, row_start_index)
  410. table_cells_flag.append(len(table_cells_result))
  411. row_start_index.append(len(table_cells_result))
  412. matched_index = match_table_and_ocr(
  413. table_cells_result, ocr_dt_boxes, table_cells_flag, table_cells_flag
  414. )
  415. pred_html = get_html_result(
  416. matched_index, ocr_texts_res, table_structure_result, row_start_index
  417. )
  418. single_img_res = {
  419. "cell_box_list": table_cells_result,
  420. "table_ocr_pred": table_ocr_pred,
  421. "pred_html": pred_html,
  422. }
  423. return SingleTableRecognitionResult(single_img_res)