batch_analyze.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import time
  2. import cv2
  3. import torch
  4. from loguru import logger
  5. from magic_pdf.config.constants import MODEL_NAME
  6. from magic_pdf.model.pdf_extract_kit import CustomPEKModel
  7. from magic_pdf.model.sub_modules.model_utils import (
  8. clean_vram, crop_img, get_res_list_from_layout_res)
  9. from magic_pdf.model.sub_modules.ocr.paddleocr.ocr_utils import (
  10. get_adjusted_mfdetrec_res, get_ocr_result_list)
  11. YOLO_LAYOUT_BASE_BATCH_SIZE = 1
  12. MFD_BASE_BATCH_SIZE = 1
  13. MFR_BASE_BATCH_SIZE = 16
  14. class BatchAnalyze:
  15. def __init__(self, model: CustomPEKModel, batch_ratio: int):
  16. self.model = model
  17. self.batch_ratio = batch_ratio
  18. def __call__(self, images: list) -> list:
  19. images_layout_res = []
  20. layout_start_time = time.time()
  21. if self.model.layout_model_name == MODEL_NAME.LAYOUTLMv3:
  22. # layoutlmv3
  23. for image in images:
  24. layout_res = self.model.layout_model(image, ignore_catids=[])
  25. images_layout_res.append(layout_res)
  26. elif self.model.layout_model_name == MODEL_NAME.DocLayout_YOLO:
  27. # doclayout_yolo
  28. layout_images = []
  29. for image_index, image in enumerate(images):
  30. layout_images.append(image)
  31. images_layout_res += self.model.layout_model.batch_predict(
  32. # layout_images, self.batch_ratio * YOLO_LAYOUT_BASE_BATCH_SIZE
  33. layout_images, YOLO_LAYOUT_BASE_BATCH_SIZE
  34. )
  35. logger.info(
  36. f'layout time: {round(time.time() - layout_start_time, 2)}, image num: {len(images)}'
  37. )
  38. if self.model.apply_formula:
  39. # 公式检测
  40. mfd_start_time = time.time()
  41. images_mfd_res = self.model.mfd_model.batch_predict(
  42. # images, self.batch_ratio * MFD_BASE_BATCH_SIZE
  43. images, MFD_BASE_BATCH_SIZE
  44. )
  45. logger.info(
  46. f'mfd time: {round(time.time() - mfd_start_time, 2)}, image num: {len(images)}'
  47. )
  48. # 公式识别
  49. mfr_start_time = time.time()
  50. images_formula_list = self.model.mfr_model.batch_predict(
  51. images_mfd_res,
  52. images,
  53. batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,
  54. )
  55. mfr_count = 0
  56. for image_index in range(len(images)):
  57. images_layout_res[image_index] += images_formula_list[image_index]
  58. mfr_count += len(images_formula_list[image_index])
  59. logger.info(
  60. f'mfr time: {round(time.time() - mfr_start_time, 2)}, image num: {mfr_count}'
  61. )
  62. # 清理显存
  63. clean_vram(self.model.device, vram_threshold=8)
  64. ocr_time = 0
  65. ocr_count = 0
  66. table_time = 0
  67. table_count = 0
  68. # reference: magic_pdf/model/doc_analyze_by_custom_model.py:doc_analyze
  69. for index in range(len(images)):
  70. layout_res = images_layout_res[index]
  71. np_array_img = images[index]
  72. ocr_res_list, table_res_list, single_page_mfdetrec_res = (
  73. get_res_list_from_layout_res(layout_res)
  74. )
  75. # ocr识别
  76. ocr_start = time.time()
  77. # Process each area that requires OCR processing
  78. for res in ocr_res_list:
  79. new_image, useful_list = crop_img(
  80. res, np_array_img, crop_paste_x=50, crop_paste_y=50
  81. )
  82. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  83. single_page_mfdetrec_res, useful_list
  84. )
  85. # OCR recognition
  86. new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
  87. if self.model.apply_ocr:
  88. ocr_res = self.model.ocr_model.ocr(
  89. new_image, mfd_res=adjusted_mfdetrec_res
  90. )[0]
  91. else:
  92. ocr_res = self.model.ocr_model.ocr(
  93. new_image, mfd_res=adjusted_mfdetrec_res, rec=False
  94. )[0]
  95. # Integration results
  96. if ocr_res:
  97. ocr_result_list = get_ocr_result_list(ocr_res, useful_list)
  98. layout_res.extend(ocr_result_list)
  99. ocr_time += time.time() - ocr_start
  100. ocr_count += len(ocr_res_list)
  101. # 表格识别 table recognition
  102. if self.model.apply_table:
  103. table_start = time.time()
  104. for res in table_res_list:
  105. new_image, _ = crop_img(res, np_array_img)
  106. single_table_start_time = time.time()
  107. html_code = None
  108. if self.model.table_model_name == MODEL_NAME.STRUCT_EQTABLE:
  109. with torch.no_grad():
  110. table_result = self.model.table_model.predict(
  111. new_image, 'html'
  112. )
  113. if len(table_result) > 0:
  114. html_code = table_result[0]
  115. elif self.model.table_model_name == MODEL_NAME.TABLE_MASTER:
  116. html_code = self.model.table_model.img2html(new_image)
  117. elif self.model.table_model_name == MODEL_NAME.RAPID_TABLE:
  118. html_code, table_cell_bboxes, logic_points, elapse = (
  119. self.model.table_model.predict(new_image)
  120. )
  121. run_time = time.time() - single_table_start_time
  122. if run_time > self.model.table_max_time:
  123. logger.warning(
  124. f'table recognition processing exceeds max time {self.model.table_max_time}s'
  125. )
  126. # 判断是否返回正常
  127. if html_code:
  128. expected_ending = html_code.strip().endswith(
  129. '</html>'
  130. ) or html_code.strip().endswith('</table>')
  131. if expected_ending:
  132. res['html'] = html_code
  133. else:
  134. logger.warning(
  135. 'table recognition processing fails, not found expected HTML table end'
  136. )
  137. else:
  138. logger.warning(
  139. 'table recognition processing fails, not get html return'
  140. )
  141. table_time += time.time() - table_start
  142. table_count += len(table_res_list)
  143. if self.model.apply_ocr:
  144. logger.info(f'ocr time: {round(ocr_time, 2)}, image num: {ocr_count}')
  145. else:
  146. logger.info(f'det time: {round(ocr_time, 2)}, image num: {ocr_count}')
  147. if self.model.apply_table:
  148. logger.info(f'table time: {round(table_time, 2)}, image num: {table_count}')
  149. return images_layout_res