result.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. import random
  16. import numpy as np
  17. import cv2
  18. import PIL
  19. import os
  20. from PIL import Image, ImageDraw, ImageFont
  21. from ....utils.fonts import PINGFANG_FONT_FILE_PATH
  22. from ..components import CVResult, HtmlMixin, XlsxMixin
  23. from typing import Any, Dict, Optional
  24. class TableRecognitionResult(CVResult, HtmlMixin, XlsxMixin):
  25. """table recognition result"""
  26. def __init__(self, data: Dict) -> None:
  27. """Initializes the object with given data and sets up mixins for HTML and XLSX processing."""
  28. super().__init__(data)
  29. HtmlMixin.__init__(self) # Initializes the HTML mixin functionality
  30. XlsxMixin.__init__(self) # Initializes the XLSX mixin functionality
  31. def save_to_html(self, save_path: str, *args, **kwargs) -> None:
  32. """
  33. Save the content to an HTML file.
  34. Args:
  35. save_path (str): The path to save the HTML file. If the path does not end with '.html',
  36. it will append '/res_table_%d.html' % self['table_region_id'] to the path.
  37. *args: Additional positional arguments to be passed to the superclass method.
  38. **kwargs: Additional keyword arguments to be passed to the superclass method.
  39. Returns:
  40. None
  41. """
  42. if not str(save_path).lower().endswith(".html"):
  43. save_path = save_path + "/res_table_%d.html" % self["table_region_id"]
  44. super().save_to_html(save_path, *args, **kwargs)
  45. def _to_html(self) -> str:
  46. """Converts the prediction to its corresponding HTML representation.
  47. Returns:
  48. str: The HTML string representation of the prediction.
  49. """
  50. return self["pred_html"]
  51. def save_to_xlsx(self, save_path: str, *args, **kwargs) -> None:
  52. """
  53. Save the content to an Excel file (.xlsx).
  54. If the save_path does not end with '.xlsx', it appends a default filename
  55. based on the table_region_id attribute.
  56. Args:
  57. save_path (str): The path where the Excel file should be saved.
  58. *args: Additional positional arguments passed to the superclass method.
  59. **kwargs: Additional keyword arguments passed to the superclass method.
  60. Returns:
  61. None
  62. """
  63. if not str(save_path).lower().endswith(".xlsx"):
  64. save_path = save_path + "/res_table_%d.xlsx" % self["table_region_id"]
  65. super().save_to_xlsx(save_path, *args, **kwargs)
  66. def _to_xlsx(self) -> str:
  67. """Converts the prediction HTML to an XLSX file path.
  68. Returns:
  69. str: The path to the XLSX file containing the prediction data.
  70. """
  71. return self["pred_html"]
  72. def save_to_img(self, save_path: str, *args, **kwargs) -> None:
  73. """
  74. Save the table and OCR result images to the specified path.
  75. Args:
  76. save_path (str): The directory path to save the images.
  77. *args: Additional positional arguments.
  78. **kwargs: Additional keyword arguments.
  79. Returns:
  80. None
  81. Raises:
  82. No specific exceptions are raised.
  83. Notes:
  84. - If save_path does not end with '.jpg' or '.png', the function appends '_res_table_cell_%d.jpg' and '_res_table_ocr_%d.jpg' to save_path
  85. with table_region_id respectively for table cell and OCR images.
  86. - The OCR result image is saved first with '_res_table_ocr_%d.jpg'.
  87. - Then the table image is saved with '_res_table_cell_%d.jpg'.
  88. - Calls the superclass's save_to_img method to save the table image.
  89. """
  90. if not str(save_path).lower().endswith((".jpg", ".png")):
  91. ocr_save_path = (
  92. save_path + "/res_table_ocr_%d.jpg" % self["table_region_id"]
  93. )
  94. save_path = save_path + "/res_table_cell_%d.jpg" % self["table_region_id"]
  95. self["table_ocr_pred"].save_to_img(ocr_save_path)
  96. super().save_to_img(save_path, *args, **kwargs)
  97. def _to_img(self) -> np.ndarray:
  98. """
  99. Convert the input image with table OCR predictions to an image with cell boundaries highlighted.
  100. Returns:
  101. np.ndarray: The input image with cell boundaries highlighted in red.
  102. """
  103. input_img = self["table_ocr_pred"]["input_img"].copy()
  104. cell_box_list = self["cell_box_list"]
  105. for box in cell_box_list:
  106. x1, y1, x2, y2 = [int(pos) for pos in box]
  107. cv2.rectangle(input_img, (x1, y1), (x2, y2), (255, 0, 0), 2)
  108. return input_img
  109. class LayoutParsingResult(dict):
  110. """Layout Parsing Result"""
  111. def __init__(self, data) -> None:
  112. """Initializes a new instance of the class with the specified data."""
  113. super().__init__(data)
  114. def save_results(self, save_path: str) -> None:
  115. """Save the layout parsing results to the specified directory.
  116. Args:
  117. save_path (str): The directory path to save the results.
  118. """
  119. if not os.path.isdir(save_path):
  120. return
  121. layout_det_res = self["layout_det_res"]
  122. save_img_path = save_path + "/layout_det_result.jpg"
  123. layout_det_res.save_to_img(save_img_path)
  124. input_params = self["input_params"]
  125. if input_params["use_doc_preprocessor"]:
  126. save_img_path = save_path + "/doc_preprocessor_result.jpg"
  127. self["doc_preprocessor_res"].save_to_img(save_img_path)
  128. if input_params["use_general_ocr"]:
  129. save_img_path = save_path + "/text_paragraphs_ocr_result.jpg"
  130. self["text_paragraphs_ocr_res"].save_to_img(save_img_path)
  131. if input_params["use_table_recognition"]:
  132. for tno in range(len(self["table_res_list"])):
  133. table_res = self["table_res_list"][tno]
  134. table_res.save_to_img(save_path)
  135. table_res.save_to_html(save_path)
  136. table_res.save_to_xlsx(save_path)
  137. if input_params["use_seal_recognition"]:
  138. for sno in range(len(self["seal_res_list"])):
  139. seal_res = self["seal_res_list"][sno]
  140. save_img_path = (
  141. save_path
  142. + "/seal_%d_recognition_result.jpg" % seal_res["seal_region_id"]
  143. )
  144. seal_res.save_to_img(save_img_path)
  145. return