table_recognition_post_processing_v2.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 math
  15. from typing import Any, Dict, Optional
  16. import numpy as np
  17. from ..layout_parsing.utils import get_sub_regions_ocr_res
  18. from ..components import convert_points_to_boxes
  19. from .result import SingleTableRecognitionResult
  20. from ..ocr.result import OCRResult
  21. def get_ori_image_coordinate(x: int, y: int, box_list: list) -> list:
  22. """
  23. get the original coordinate from Cropped image to Original image.
  24. Args:
  25. x (int): x coordinate of cropped image
  26. y (int): y coordinate of cropped image
  27. box_list (list): list of table bounding boxes, eg. [[x1, y1, x2, y2, x3, y3, x4, y4]]
  28. Returns:
  29. list: list of original coordinates, eg. [[x1, y1, x2, y2, x3, y3, x4, y4]]
  30. """
  31. if not box_list:
  32. return box_list
  33. offset = np.array([x, y] * 4)
  34. box_list = np.array(box_list)
  35. if box_list.shape[-1] == 2:
  36. offset = offset.reshape(4, 2)
  37. ori_box_list = offset + box_list
  38. return ori_box_list
  39. def convert_table_structure_pred_bbox(
  40. cell_points_list: list, crop_start_point: list, img_shape: tuple
  41. ) -> None:
  42. """
  43. Convert the predicted table structure bounding boxes to the original image coordinate system.
  44. Args:
  45. cell_points_list (list): Bounding boxes ('bbox').
  46. crop_start_point (list): A list of two integers representing the starting point (x, y) of the cropped image region.
  47. img_shape (tuple): A tuple of two integers representing the shape (height, width) of the original image.
  48. Returns:
  49. cell_points_list (list): Bounding boxes ('bbox').
  50. """
  51. ori_cell_points_list = get_ori_image_coordinate(
  52. crop_start_point[0], crop_start_point[1], cell_points_list
  53. )
  54. ori_cell_points_list = np.reshape(ori_cell_points_list, (-1, 4, 2))
  55. cell_box_list = convert_points_to_boxes(ori_cell_points_list)
  56. img_height, img_width = img_shape
  57. cell_box_list = np.clip(
  58. cell_box_list, 0, [img_width, img_height, img_width, img_height]
  59. )
  60. return cell_box_list
  61. def distance(box_1: list, box_2: list) -> float:
  62. """
  63. compute the distance between two boxes
  64. Args:
  65. box_1 (list): first rectangle box,eg.(x1, y1, x2, y2)
  66. box_2 (list): second rectangle box,eg.(x1, y1, x2, y2)
  67. Returns:
  68. float: the distance between two boxes
  69. """
  70. x1, y1, x2, y2 = box_1
  71. x3, y3, x4, y4 = box_2
  72. center1_x = (x1 + x2) / 2
  73. center1_y = (y1 + y2) / 2
  74. center2_x = (x3 + x4) / 2
  75. center2_y = (y3 + y4) / 2
  76. dis = math.sqrt((center2_x - center1_x) ** 2 + (center2_y - center1_y) ** 2)
  77. dis_2 = abs(x3 - x1) + abs(y3 - y1)
  78. dis_3 = abs(x4 - x2) + abs(y4 - y2)
  79. return dis + min(dis_2, dis_3)
  80. def compute_iou(rec1: list, rec2: list) -> float:
  81. """
  82. computing IoU
  83. Args:
  84. rec1 (list): (x1, y1, x2, y2)
  85. rec2 (list): (x1, y1, x2, y2)
  86. Returns:
  87. float: Intersection over Union
  88. """
  89. # computing area of each rectangles
  90. S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
  91. S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
  92. # computing the sum_area
  93. sum_area = S_rec1 + S_rec2
  94. # find the each edge of intersect rectangle
  95. left_line = max(rec1[0], rec2[0])
  96. right_line = min(rec1[2], rec2[2])
  97. top_line = max(rec1[1], rec2[1])
  98. bottom_line = min(rec1[3], rec2[3])
  99. # judge if there is an intersect
  100. if left_line >= right_line or top_line >= bottom_line:
  101. return 0.0
  102. else:
  103. intersect = (right_line - left_line) * (bottom_line - top_line)
  104. return (intersect / (sum_area - intersect)) * 1.0
  105. def compute_inter(rec1, rec2):
  106. """
  107. computing intersection over rec2_area
  108. Args:
  109. rec1 (list): (x1, y1, x2, y2)
  110. rec2 (list): (x1, y1, x2, y2)
  111. Returns:
  112. float: Intersection over rec2_area
  113. """
  114. x1_1, y1_1, x2_1, y2_1 = rec1
  115. x1_2, y1_2, x2_2, y2_2 = rec2
  116. x_left = max(x1_1, x1_2)
  117. y_top = max(y1_1, y1_2)
  118. x_right = min(x2_1, x2_2)
  119. y_bottom = min(y2_1, y2_2)
  120. inter_width = max(0, x_right - x_left)
  121. inter_height = max(0, y_bottom - y_top)
  122. inter_area = inter_width * inter_height
  123. rec2_area = (x2_2 - x1_2) * (y2_2 - y1_2)
  124. if rec2_area == 0:
  125. return 0
  126. iou = inter_area / rec2_area
  127. return iou
  128. def match_table_and_ocr(cell_box_list: list, ocr_dt_boxes: list) -> dict:
  129. """
  130. match table and ocr
  131. Args:
  132. cell_box_list (list): bbox for table cell, 2 points, [left, top, right, bottom]
  133. ocr_dt_boxes (list): bbox for ocr, 2 points, [left, top, right, bottom]
  134. Returns:
  135. dict: matched dict, key is table index, value is ocr index
  136. """
  137. matched = {}
  138. del_ocr = []
  139. for i, table_box in enumerate(cell_box_list):
  140. if len(table_box) == 8:
  141. table_box = [
  142. np.min(table_box[0::2]),
  143. np.min(table_box[1::2]),
  144. np.max(table_box[0::2]),
  145. np.max(table_box[1::2]),
  146. ]
  147. for j, ocr_box in enumerate(np.array(ocr_dt_boxes)):
  148. if compute_inter(table_box, ocr_box) > 0.8:
  149. if i not in matched.keys():
  150. matched[i] = [j]
  151. else:
  152. matched[i].append(j)
  153. del_ocr.append(j)
  154. miss_ocr = []
  155. miss_ocr_index = []
  156. for m in range(len(ocr_dt_boxes)):
  157. if m not in del_ocr:
  158. miss_ocr.append(ocr_dt_boxes[m])
  159. miss_ocr_index.append(m)
  160. if len(miss_ocr) != 0:
  161. for k, miss_ocr_box in enumerate(miss_ocr):
  162. distances = []
  163. for q, table_box in enumerate(cell_box_list):
  164. if len(table_box) == 0:
  165. continue
  166. if len(table_box) == 8:
  167. table_box = [
  168. np.min(table_box[0::2]),
  169. np.min(table_box[1::2]),
  170. np.max(table_box[0::2]),
  171. np.max(table_box[1::2]),
  172. ]
  173. distances.append(
  174. (distance(table_box, miss_ocr_box), 1.0 - compute_iou(table_box, miss_ocr_box))
  175. ) # compute iou and l1 distance
  176. sorted_distances = distances.copy()
  177. # select det box by iou and l1 distance
  178. sorted_distances = sorted(sorted_distances, key=lambda item: (item[1], item[0]))
  179. if distances.index(sorted_distances[0]) not in matched.keys():
  180. matched[distances.index(sorted_distances[0])] = [miss_ocr_index[k]]
  181. else:
  182. matched[distances.index(sorted_distances[0])].append(miss_ocr_index[k])
  183. # print(matched)
  184. return matched
  185. def get_html_result(
  186. matched_index: dict, ocr_contents: dict, pred_structures: list
  187. ) -> str:
  188. """
  189. Generates HTML content based on the matched index, OCR contents, and predicted structures.
  190. Args:
  191. matched_index (dict): A dictionary containing matched indices.
  192. ocr_contents (dict): A dictionary of OCR contents.
  193. pred_structures (list): A list of predicted HTML structures.
  194. Returns:
  195. str: Generated HTML content as a string.
  196. """
  197. pred_html = []
  198. td_index = 0
  199. head_structure = pred_structures[0:3]
  200. html = "".join(head_structure)
  201. table_structure = pred_structures[3:-3]
  202. for tag in table_structure:
  203. if "</td>" in tag:
  204. if "<td></td>" == tag:
  205. pred_html.extend("<td>")
  206. if td_index in matched_index.keys():
  207. if len(matched_index[td_index])==0:
  208. continue
  209. b_with = False
  210. if (
  211. "<b>" in ocr_contents[matched_index[td_index][0]]
  212. and len(matched_index[td_index]) > 1
  213. ):
  214. b_with = True
  215. pred_html.extend("<b>")
  216. for i, td_index_index in enumerate(matched_index[td_index]):
  217. content = ocr_contents[td_index_index]
  218. if len(matched_index[td_index]) > 1:
  219. if len(content) == 0:
  220. continue
  221. if content[0] == " ":
  222. content = content[1:]
  223. if "<b>" in content:
  224. content = content[3:]
  225. if "</b>" in content:
  226. content = content[:-4]
  227. if len(content) == 0:
  228. continue
  229. if i != len(matched_index[td_index]) - 1 and " " != content[-1]:
  230. content += " "
  231. pred_html.extend(content)
  232. if b_with:
  233. pred_html.extend("</b>")
  234. if "<td></td>" == tag:
  235. pred_html.append("</td>")
  236. else:
  237. pred_html.append(tag)
  238. td_index += 1
  239. else:
  240. pred_html.append(tag)
  241. html += "".join(pred_html)
  242. end_structure = pred_structures[-3:]
  243. html += "".join(end_structure)
  244. return html
  245. def sort_table_cells_boxes(boxes):
  246. """
  247. Sort the input list of bounding boxes.
  248. Args:
  249. boxes (list of lists): The input list of bounding boxes, where each bounding box is formatted as [x1, y1, x2, y2].
  250. Returns:
  251. sorted_boxes (list of lists): The list of bounding boxes sorted.
  252. """
  253. boxes_sorted_by_y = sorted(boxes, key=lambda box: box[1])
  254. rows = []
  255. current_row = []
  256. current_y = None
  257. tolerance = 10
  258. for box in boxes_sorted_by_y:
  259. x1, y1, x2, y2 = box
  260. if current_y is None:
  261. current_row.append(box)
  262. current_y = y1
  263. else:
  264. if abs(y1 - current_y) <= tolerance:
  265. current_row.append(box)
  266. else:
  267. current_row.sort(key=lambda x: x[0])
  268. rows.append(current_row)
  269. current_row = [box]
  270. current_y = y1
  271. if current_row:
  272. current_row.sort(key=lambda x: x[0])
  273. rows.append(current_row)
  274. sorted_boxes = [box for row in rows for box in row]
  275. return sorted_boxes
  276. def convert_to_four_point_coordinates(boxes):
  277. """
  278. Convert bounding boxes from [x1, y1, x2, y2] format to
  279. [x1, y1, x2, y1, x2, y2, x1, y2] format.
  280. Parameters:
  281. - boxes: A list of bounding boxes, each defined as a list of integers
  282. in the format [x1, y1, x2, y2].
  283. Returns:
  284. - A list of bounding boxes, each converted to the format
  285. [x1, y1, x2, y1, x2, y2, x1, y2].
  286. """
  287. # Initialize an empty list to store the converted bounding boxes
  288. converted_boxes = []
  289. # Loop over each box in the input list
  290. for box in boxes:
  291. x1, y1, x2, y2 = box
  292. # Define the four corner points
  293. top_left = (x1, y1)
  294. top_right = (x2, y1)
  295. bottom_right = (x2, y2)
  296. bottom_left = (x1, y2)
  297. # Create a new list for the converted box
  298. converted_box = [
  299. top_left[0], top_left[1], # Top-left corner
  300. top_right[0], top_right[1], # Top-right corner
  301. bottom_right[0], bottom_right[1], # Bottom-right corner
  302. bottom_left[0], bottom_left[1] # Bottom-left corner
  303. ]
  304. # Append the converted box to the list
  305. converted_boxes.append(converted_box)
  306. return converted_boxes
  307. def get_table_recognition_res(
  308. table_box: list,
  309. table_structure_result: list,
  310. table_cells_result: list,
  311. overall_ocr_res: OCRResult,
  312. ) -> SingleTableRecognitionResult:
  313. """
  314. Retrieve table recognition result from cropped image info, table structure prediction, and overall OCR result.
  315. Args:
  316. table_box (list): Information about the location of cropped image, including the bounding box.
  317. table_structure_result (list): Predicted table structure.
  318. table_cells_result (list): Predicted table cells.
  319. overall_ocr_res (OCRResult): Overall OCR result from the input image.
  320. Returns:
  321. SingleTableRecognitionResult: An object containing the single table recognition result.
  322. """
  323. table_cells_result = convert_to_four_point_coordinates(table_cells_result)
  324. table_box = np.array([table_box])
  325. table_ocr_pred = get_sub_regions_ocr_res(overall_ocr_res, table_box)
  326. crop_start_point = [table_box[0][0], table_box[0][1]]
  327. img_shape = overall_ocr_res["doc_preprocessor_res"]["output_img"].shape[0:2]
  328. table_cells_result = convert_table_structure_pred_bbox(
  329. table_cells_result, crop_start_point, img_shape
  330. )
  331. ocr_dt_boxes = table_ocr_pred["rec_boxes"]
  332. ocr_texts_res = table_ocr_pred["rec_texts"]
  333. table_cells_result = sort_table_cells_boxes(table_cells_result)
  334. matched_index = match_table_and_ocr(table_cells_result, ocr_dt_boxes)
  335. pred_html = get_html_result(matched_index, ocr_texts_res, table_structure_result)
  336. single_img_res = {
  337. "cell_box_list": table_cells_result,
  338. "table_ocr_pred": table_ocr_pred,
  339. "pred_html": pred_html,
  340. }
  341. return SingleTableRecognitionResult(single_img_res)