rapid_table.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import os
  2. import html
  3. import cv2
  4. import numpy as np
  5. from loguru import logger
  6. from rapid_table import RapidTable, RapidTableInput
  7. from mineru.utils.enum_class import ModelPath
  8. from mineru.utils.models_download_utils import auto_download_and_get_model_root_path
  9. def escape_html(input_string):
  10. """Escape HTML Entities."""
  11. return html.escape(input_string)
  12. class RapidTableModel(object):
  13. def __init__(self, ocr_engine):
  14. slanet_plus_model_path = os.path.join(auto_download_and_get_model_root_path(ModelPath.slanet_plus), ModelPath.slanet_plus)
  15. input_args = RapidTableInput(model_type='slanet_plus', model_path=slanet_plus_model_path)
  16. self.table_model = RapidTable(input_args)
  17. self.ocr_engine = ocr_engine
  18. def predict(self, image):
  19. bgr_image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
  20. # First check the overall image aspect ratio (height/width)
  21. img_height, img_width = bgr_image.shape[:2]
  22. img_aspect_ratio = img_height / img_width if img_width > 0 else 1.0
  23. img_is_portrait = img_aspect_ratio > 1.2
  24. if img_is_portrait:
  25. det_res = self.ocr_engine.ocr(bgr_image, rec=False)[0]
  26. # Check if table is rotated by analyzing text box aspect ratios
  27. is_rotated = False
  28. if det_res:
  29. vertical_count = 0
  30. for box_ocr_res in det_res:
  31. p1, p2, p3, p4 = box_ocr_res
  32. # Calculate width and height
  33. width = p3[0] - p1[0]
  34. height = p3[1] - p1[1]
  35. aspect_ratio = width / height if height > 0 else 1.0
  36. # Count vertical vs horizontal text boxes
  37. if aspect_ratio < 0.8: # Taller than wide - vertical text
  38. vertical_count += 1
  39. # elif aspect_ratio > 1.2: # Wider than tall - horizontal text
  40. # horizontal_count += 1
  41. # If we have more vertical text boxes than horizontal ones,
  42. # and vertical ones are significant, table might be rotated
  43. if vertical_count >= len(det_res) * 0.3:
  44. is_rotated = True
  45. # logger.debug(f"Text orientation analysis: vertical={vertical_count}, det_res={len(det_res)}, rotated={is_rotated}")
  46. # Rotate image if necessary
  47. if is_rotated:
  48. # logger.debug("Table appears to be in portrait orientation, rotating 90 degrees clockwise")
  49. image = cv2.rotate(np.asarray(image), cv2.ROTATE_90_CLOCKWISE)
  50. bgr_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
  51. # Continue with OCR on potentially rotated image
  52. ocr_result = self.ocr_engine.ocr(bgr_image)[0]
  53. if ocr_result:
  54. ocr_result = [[item[0], escape_html(item[1][0]), item[1][1]] for item in ocr_result if
  55. len(item) == 2 and isinstance(item[1], tuple)]
  56. else:
  57. ocr_result = None
  58. if ocr_result:
  59. try:
  60. table_results = self.table_model(np.asarray(image), ocr_result)
  61. html_code = table_results.pred_html
  62. table_cell_bboxes = table_results.cell_bboxes
  63. logic_points = table_results.logic_points
  64. elapse = table_results.elapse
  65. return html_code, table_cell_bboxes, logic_points, elapse
  66. except Exception as e:
  67. logger.exception(e)
  68. return None, None, None, None