batch_analyze.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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.paddleocr2pytorch.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. det_time = 0
  74. det_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. det_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, ocr_enable, new_image, _lang)
  109. layout_res.extend(ocr_result_list)
  110. det_time += time.time() - det_start
  111. det_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. logger.info(f'ocr-det time: {round(det_time, 2)}, image num: {det_count}')
  155. if self.model.apply_table:
  156. logger.info(f'table time: {round(table_time, 2)}, image num: {table_count}')
  157. # Create dictionaries to store items by language
  158. need_ocr_lists_by_lang = {} # Dict of lists for each language
  159. img_crop_lists_by_lang = {} # Dict of lists for each language
  160. for layout_res in images_layout_res:
  161. for layout_res_item in layout_res:
  162. if layout_res_item['category_id'] in [15]:
  163. if 'np_img' in layout_res_item and 'lang' in layout_res_item:
  164. lang = layout_res_item['lang']
  165. # Initialize lists for this language if not exist
  166. if lang not in need_ocr_lists_by_lang:
  167. need_ocr_lists_by_lang[lang] = []
  168. img_crop_lists_by_lang[lang] = []
  169. # Add to the appropriate language-specific lists
  170. need_ocr_lists_by_lang[lang].append(layout_res_item)
  171. img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])
  172. # Remove the fields after adding to lists
  173. layout_res_item.pop('np_img')
  174. layout_res_item.pop('lang')
  175. if len(img_crop_lists_by_lang) > 0:
  176. # Process OCR by language
  177. rec_time = 0
  178. rec_start = time.time()
  179. total_processed = 0
  180. # Process each language separately
  181. for lang, img_crop_list in img_crop_lists_by_lang.items():
  182. if len(img_crop_list) > 0:
  183. # Get OCR results for this language's images
  184. ocr_res_list = self.model.ocr_model.ocr(img_crop_list, det=False)[0]
  185. need_ocr_list = need_ocr_lists_by_lang[lang]
  186. # Verify we have matching counts
  187. assert len(ocr_res_list) == len(
  188. need_ocr_list), f'ocr_res_list: {len(ocr_res_list)}, need_ocr_list: {len(need_ocr_list)} for lang: {lang}'
  189. # Process OCR results for this language
  190. for index, layout_res_item in enumerate(need_ocr_list):
  191. ocr_text, ocr_score = ocr_res_list[index]
  192. layout_res_item['text'] = ocr_text
  193. layout_res_item['score'] = float(round(ocr_score, 2))
  194. total_processed += len(img_crop_list)
  195. rec_time += time.time() - rec_start
  196. logger.info(f'ocr-rec time: {round(rec_time, 2)}, total images processed: {total_processed}')
  197. return images_layout_res