table_recognition_post_processing_v2.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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, ocr_dt_boxes, table_cells_flag, row_start_index):
  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. all_matched = []
  138. for k in range(len(table_cells_flag)-1):
  139. matched = {}
  140. for i, table_box in enumerate(cell_box_list[table_cells_flag[k]:table_cells_flag[k+1]]):
  141. if len(table_box) == 8:
  142. table_box = [
  143. np.min(table_box[0::2]),
  144. np.min(table_box[1::2]),
  145. np.max(table_box[0::2]),
  146. np.max(table_box[1::2]),
  147. ]
  148. for j, ocr_box in enumerate(np.array(ocr_dt_boxes)):
  149. if compute_inter(table_box, ocr_box) > 0.7:
  150. if i not in matched.keys():
  151. matched[i] = [j]
  152. else:
  153. matched[i].append(j)
  154. real_len=max(matched.keys())+1 if len(matched)!=0 else 0
  155. if table_cells_flag[k+1] < row_start_index[k+1]:
  156. for s in range(row_start_index[k+1]-table_cells_flag[k+1]):
  157. matched[real_len+s] = []
  158. elif table_cells_flag[k+1] > row_start_index[k+1]:
  159. for s in range(table_cells_flag[k+1]-row_start_index[k+1]):
  160. matched[real_len-1].append(matched[real_len+s])
  161. all_matched.append(matched)
  162. return all_matched
  163. def get_html_result(
  164. all_matched_index: dict, ocr_contents: dict, pred_structures: list, table_cells_flag
  165. ) -> str:
  166. """
  167. Generates HTML content based on the matched index, OCR contents, and predicted structures.
  168. Args:
  169. matched_index (dict): A dictionary containing matched indices.
  170. ocr_contents (dict): A dictionary of OCR contents.
  171. pred_structures (list): A list of predicted HTML structures.
  172. Returns:
  173. str: Generated HTML content as a string.
  174. """
  175. pred_html = []
  176. td_index = 0
  177. td_count = 0
  178. matched_list_index = 0
  179. head_structure = pred_structures[0:3]
  180. html = "".join(head_structure)
  181. table_structure = pred_structures[3:-3]
  182. for tag in table_structure:
  183. matched_index = all_matched_index[matched_list_index]
  184. if "</td>" in tag:
  185. if "<td></td>" == tag:
  186. pred_html.extend("<td>")
  187. if td_index in matched_index.keys():
  188. if len(matched_index[td_index])==0:
  189. continue
  190. b_with = False
  191. if (
  192. "<b>" in ocr_contents[matched_index[td_index][0]]
  193. and len(matched_index[td_index]) > 1
  194. ):
  195. b_with = True
  196. pred_html.extend("<b>")
  197. for i, td_index_index in enumerate(matched_index[td_index]):
  198. content = ocr_contents[td_index_index]
  199. if len(matched_index[td_index]) > 1:
  200. if len(content) == 0:
  201. continue
  202. if content[0] == " ":
  203. content = content[1:]
  204. if "<b>" in content:
  205. content = content[3:]
  206. if "</b>" in content:
  207. content = content[:-4]
  208. if len(content) == 0:
  209. continue
  210. if i != len(matched_index[td_index]) - 1 and " " != content[-1]:
  211. content += " "
  212. pred_html.extend(content)
  213. if b_with:
  214. pred_html.extend("</b>")
  215. if "<td></td>" == tag:
  216. pred_html.append("</td>")
  217. else:
  218. pred_html.append(tag)
  219. td_index += 1
  220. td_count += 1
  221. if td_count>=table_cells_flag[matched_list_index+1] and matched_list_index<len(all_matched_index)-1:
  222. matched_list_index += 1
  223. td_index = 0
  224. else:
  225. pred_html.append(tag)
  226. html += "".join(pred_html)
  227. end_structure = pred_structures[-3:]
  228. html += "".join(end_structure)
  229. return html
  230. def sort_table_cells_boxes(boxes):
  231. """
  232. Sort the input list of bounding boxes.
  233. Args:
  234. boxes (list of lists): The input list of bounding boxes, where each bounding box is formatted as [x1, y1, x2, y2].
  235. Returns:
  236. sorted_boxes (list of lists): The list of bounding boxes sorted.
  237. """
  238. boxes_sorted_by_y = sorted(boxes, key=lambda box: box[1])
  239. rows = []
  240. current_row = []
  241. current_y = None
  242. tolerance = 10
  243. for box in boxes_sorted_by_y:
  244. x1, y1, x2, y2 = box
  245. if current_y is None:
  246. current_row.append(box)
  247. current_y = y1
  248. else:
  249. if abs(y1 - current_y) <= tolerance:
  250. current_row.append(box)
  251. else:
  252. current_row.sort(key=lambda x: x[0])
  253. rows.append(current_row)
  254. current_row = [box]
  255. current_y = y1
  256. if current_row:
  257. current_row.sort(key=lambda x: x[0])
  258. rows.append(current_row)
  259. sorted_boxes = []
  260. flag = [0]
  261. for i in range(len(rows)):
  262. sorted_boxes.extend(rows[i])
  263. if i < len(rows):
  264. flag.append(flag[i] + len(rows[i]))
  265. return sorted_boxes, flag
  266. def convert_to_four_point_coordinates(boxes):
  267. """
  268. Convert bounding boxes from [x1, y1, x2, y2] format to
  269. [x1, y1, x2, y1, x2, y2, x1, y2] format.
  270. Parameters:
  271. - boxes: A list of bounding boxes, each defined as a list of integers
  272. in the format [x1, y1, x2, y2].
  273. Returns:
  274. - A list of bounding boxes, each converted to the format
  275. [x1, y1, x2, y1, x2, y2, x1, y2].
  276. """
  277. # Initialize an empty list to store the converted bounding boxes
  278. converted_boxes = []
  279. # Loop over each box in the input list
  280. for box in boxes:
  281. x1, y1, x2, y2 = box
  282. # Define the four corner points
  283. top_left = (x1, y1)
  284. top_right = (x2, y1)
  285. bottom_right = (x2, y2)
  286. bottom_left = (x1, y2)
  287. # Create a new list for the converted box
  288. converted_box = [
  289. top_left[0], top_left[1], # Top-left corner
  290. top_right[0], top_right[1], # Top-right corner
  291. bottom_right[0], bottom_right[1], # Bottom-right corner
  292. bottom_left[0], bottom_left[1] # Bottom-left corner
  293. ]
  294. # Append the converted box to the list
  295. converted_boxes.append(converted_box)
  296. return converted_boxes
  297. def find_row_start_index(html_list):
  298. """
  299. find the index of the first cell in each row
  300. Args:
  301. html_list (list): list for html results
  302. Returns:
  303. row_start_indices (list): list for the index of the first cell in each row
  304. """
  305. # Initialize an empty list to store the indices of row start positions
  306. row_start_indices = []
  307. # Variable to track the current index in the flattened HTML content
  308. current_index = 0
  309. # Flag to check if we are inside a table row
  310. inside_row = False
  311. # Iterate through the HTML tags
  312. for keyword in html_list:
  313. # If a new row starts, set the inside_row flag to True
  314. if keyword == "<tr>":
  315. inside_row = True
  316. # If we encounter a closing row tag, set the inside_row flag to False
  317. elif keyword == "</tr>":
  318. inside_row = False
  319. # If we encounter a cell and we are inside a row
  320. elif (keyword == "<td></td>" or keyword == "</td>") and inside_row:
  321. # Append the current index as the starting index of the row
  322. row_start_indices.append(current_index)
  323. # Set the flag to ensure we only record the first cell of the current row
  324. inside_row = False
  325. # Increment the current index if we encounter a cell regardless of being inside a row or not
  326. if keyword == "<td></td>" or keyword == "</td>":
  327. current_index += 1
  328. # Return the computed starting indices of each row
  329. return row_start_indices
  330. def map_and_get_max(table_cells_flag, row_start_index):
  331. """
  332. Retrieve table recognition result from cropped image info, table structure prediction, and overall OCR result.
  333. Args:
  334. table_cells_flag (list): List of the flags representing the end of each row of the table cells detection results.
  335. row_start_index (list): List of the flags representing the end of each row of the table structure predicted results.
  336. Returns:
  337. max_values: List of the process results.
  338. """
  339. max_values = []
  340. i = 0
  341. max_value = None
  342. for j in range(len(row_start_index)):
  343. while i < len(table_cells_flag) and table_cells_flag[i] <= row_start_index[j]:
  344. if max_value is None or table_cells_flag[i] > max_value:
  345. max_value = table_cells_flag[i]
  346. i += 1
  347. max_values.append(max_value if max_value is not None else row_start_index[j])
  348. return max_values
  349. def get_table_recognition_res(
  350. table_box: list,
  351. table_structure_result: list,
  352. table_cells_result: list,
  353. overall_ocr_res: OCRResult,
  354. cells_texts_list: list,
  355. use_table_cells_ocr_results: bool,
  356. ) -> SingleTableRecognitionResult:
  357. """
  358. Retrieve table recognition result from cropped image info, table structure prediction, and overall OCR result.
  359. Args:
  360. table_box (list): Information about the location of cropped image, including the bounding box.
  361. table_structure_result (list): Predicted table structure.
  362. table_cells_result (list): Predicted table cells.
  363. overall_ocr_res (OCRResult): Overall OCR result from the input image.
  364. cells_texts_list (list): OCR results with cells.
  365. use_table_cells_ocr_results (bool): whether to use OCR results with cells.
  366. Returns:
  367. SingleTableRecognitionResult: An object containing the single table recognition result.
  368. """
  369. table_cells_result = convert_to_four_point_coordinates(table_cells_result)
  370. table_box = np.array([table_box])
  371. table_ocr_pred = get_sub_regions_ocr_res(overall_ocr_res, table_box)
  372. crop_start_point = [table_box[0][0], table_box[0][1]]
  373. img_shape = overall_ocr_res["doc_preprocessor_res"]["output_img"].shape[0:2]
  374. if len(table_cells_result) == 0 or len(table_ocr_pred["rec_boxes"]) == 0:
  375. pred_html = ' '.join(table_structure_result)
  376. if len(table_cells_result) != 0:
  377. table_cells_result = convert_table_structure_pred_bbox(
  378. table_cells_result, crop_start_point, img_shape
  379. )
  380. single_img_res = {
  381. "cell_box_list": table_cells_result,
  382. "table_ocr_pred": table_ocr_pred,
  383. "pred_html": pred_html,
  384. }
  385. return SingleTableRecognitionResult(single_img_res)
  386. table_cells_result = convert_table_structure_pred_bbox(
  387. table_cells_result, crop_start_point, img_shape
  388. )
  389. if use_table_cells_ocr_results == True:
  390. ocr_dt_boxes = table_cells_result
  391. ocr_texts_res = cells_texts_list
  392. else:
  393. ocr_dt_boxes = table_ocr_pred["rec_boxes"]
  394. ocr_texts_res = table_ocr_pred["rec_texts"]
  395. table_cells_result, table_cells_flag = sort_table_cells_boxes(table_cells_result)
  396. row_start_index = find_row_start_index(table_structure_result)
  397. table_cells_flag = map_and_get_max(table_cells_flag, row_start_index)
  398. table_cells_flag.append(len(table_cells_result))
  399. row_start_index.append(len(table_cells_result))
  400. matched_index = match_table_and_ocr(table_cells_result, ocr_dt_boxes, table_cells_flag, table_cells_flag)
  401. pred_html = get_html_result(matched_index, ocr_texts_res, table_structure_result, row_start_index)
  402. single_img_res = {
  403. "cell_box_list": table_cells_result,
  404. "table_ocr_pred": table_ocr_pred,
  405. "pred_html": pred_html,
  406. }
  407. return SingleTableRecognitionResult(single_img_res)