batch_analyze.py 7.6 KB

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