batch_analyze.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import time
  2. import cv2
  3. from loguru import logger
  4. from tqdm import tqdm
  5. from magic_pdf.config.constants import MODEL_NAME
  6. from magic_pdf.model.sub_modules.model_init import AtomModelSingleton
  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. ocr_res_list_all_page = []
  74. table_res_list_all_page = []
  75. for index in range(len(images)):
  76. _, ocr_enable, _lang = images_with_extra_info[index]
  77. layout_res = images_layout_res[index]
  78. np_array_img = images[index]
  79. ocr_res_list, table_res_list, single_page_mfdetrec_res = (
  80. get_res_list_from_layout_res(layout_res)
  81. )
  82. ocr_res_list_all_page.append({'ocr_res_list':ocr_res_list,
  83. 'lang':_lang,
  84. 'ocr_enable':ocr_enable,
  85. 'np_array_img':np_array_img,
  86. 'single_page_mfdetrec_res':single_page_mfdetrec_res,
  87. 'layout_res':layout_res,
  88. })
  89. for table_res in table_res_list:
  90. table_img, _ = crop_img(table_res, np_array_img)
  91. table_res_list_all_page.append({'table_res':table_res,
  92. 'lang':_lang,
  93. 'table_img':table_img,
  94. })
  95. # 文本框检测
  96. det_start = time.time()
  97. det_count = 0
  98. # for ocr_res_list_dict in ocr_res_list_all_page:
  99. for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):
  100. # Process each area that requires OCR processing
  101. _lang = ocr_res_list_dict['lang']
  102. # Get OCR results for this language's images
  103. atom_model_manager = AtomModelSingleton()
  104. ocr_model = atom_model_manager.get_atom_model(
  105. atom_model_name='ocr',
  106. ocr_show_log=False,
  107. det_db_box_thresh=0.3,
  108. lang=_lang
  109. )
  110. for res in ocr_res_list_dict['ocr_res_list']:
  111. new_image, useful_list = crop_img(
  112. res, ocr_res_list_dict['np_array_img'], crop_paste_x=50, crop_paste_y=50
  113. )
  114. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  115. ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
  116. )
  117. # OCR-det
  118. new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
  119. ocr_res = ocr_model.ocr(
  120. new_image, mfd_res=adjusted_mfdetrec_res, rec=False
  121. )[0]
  122. # Integration results
  123. if ocr_res:
  124. ocr_result_list = get_ocr_result_list(ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], new_image, _lang)
  125. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  126. det_count += len(ocr_res_list_dict['ocr_res_list'])
  127. # logger.info(f'ocr-det time: {round(time.time()-det_start, 2)}, image num: {det_count}')
  128. # 表格识别 table recognition
  129. if self.model.apply_table:
  130. table_start = time.time()
  131. table_count = 0
  132. # for table_res_list_dict in table_res_list_all_page:
  133. for table_res_dict in tqdm(table_res_list_all_page, desc="Table Predict"):
  134. _lang = table_res_dict['lang']
  135. atom_model_manager = AtomModelSingleton()
  136. ocr_engine = atom_model_manager.get_atom_model(
  137. atom_model_name='ocr',
  138. ocr_show_log=False,
  139. det_db_box_thresh=0.5,
  140. det_db_unclip_ratio=1.6,
  141. lang=_lang
  142. )
  143. table_model = atom_model_manager.get_atom_model(
  144. atom_model_name='table',
  145. table_model_name='rapid_table',
  146. table_model_path='',
  147. table_max_time=400,
  148. device='cpu',
  149. ocr_engine=ocr_engine,
  150. table_sub_model_name='slanet_plus'
  151. )
  152. html_code, table_cell_bboxes, logic_points, elapse = table_model.predict(table_res_dict['table_img'])
  153. # 判断是否返回正常
  154. if html_code:
  155. expected_ending = html_code.strip().endswith(
  156. '</html>'
  157. ) or html_code.strip().endswith('</table>')
  158. if expected_ending:
  159. table_res_dict['table_res']['html'] = html_code
  160. else:
  161. logger.warning(
  162. 'table recognition processing fails, not found expected HTML table end'
  163. )
  164. else:
  165. logger.warning(
  166. 'table recognition processing fails, not get html return'
  167. )
  168. # logger.info(f'table time: {round(time.time() - table_start, 2)}, image num: {len(table_res_list_all_page)}')
  169. # Create dictionaries to store items by language
  170. need_ocr_lists_by_lang = {} # Dict of lists for each language
  171. img_crop_lists_by_lang = {} # Dict of lists for each language
  172. for layout_res in images_layout_res:
  173. for layout_res_item in layout_res:
  174. if layout_res_item['category_id'] in [15]:
  175. if 'np_img' in layout_res_item and 'lang' in layout_res_item:
  176. lang = layout_res_item['lang']
  177. # Initialize lists for this language if not exist
  178. if lang not in need_ocr_lists_by_lang:
  179. need_ocr_lists_by_lang[lang] = []
  180. img_crop_lists_by_lang[lang] = []
  181. # Add to the appropriate language-specific lists
  182. need_ocr_lists_by_lang[lang].append(layout_res_item)
  183. img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])
  184. # Remove the fields after adding to lists
  185. layout_res_item.pop('np_img')
  186. layout_res_item.pop('lang')
  187. if len(img_crop_lists_by_lang) > 0:
  188. # Process OCR by language
  189. rec_time = 0
  190. rec_start = time.time()
  191. total_processed = 0
  192. # Process each language separately
  193. for lang, img_crop_list in img_crop_lists_by_lang.items():
  194. if len(img_crop_list) > 0:
  195. # Get OCR results for this language's images
  196. atom_model_manager = AtomModelSingleton()
  197. ocr_model = atom_model_manager.get_atom_model(
  198. atom_model_name='ocr',
  199. ocr_show_log=False,
  200. det_db_box_thresh=0.3,
  201. lang=lang
  202. )
  203. ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]
  204. # Verify we have matching counts
  205. assert len(ocr_res_list) == len(
  206. need_ocr_lists_by_lang[lang]), f'ocr_res_list: {len(ocr_res_list)}, need_ocr_list: {len(need_ocr_lists_by_lang[lang])} for lang: {lang}'
  207. # Process OCR results for this language
  208. for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):
  209. ocr_text, ocr_score = ocr_res_list[index]
  210. layout_res_item['text'] = ocr_text
  211. layout_res_item['score'] = float(round(ocr_score, 2))
  212. total_processed += len(img_crop_list)
  213. rec_time += time.time() - rec_start
  214. # logger.info(f'ocr-rec time: {round(rec_time, 2)}, total images processed: {total_processed}')
  215. return images_layout_res