batch_analyze.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. self.model = self.model_manager.get_model(
  28. ocr=True,
  29. show_log=self.show_log,
  30. lang = None,
  31. layout_model = self.layout_model,
  32. formula_enable = self.formula_enable,
  33. table_enable = self.table_enable,
  34. )
  35. images = [image for image, _, _ in images_with_extra_info]
  36. if self.model.layout_model_name == MODEL_NAME.LAYOUTLMv3:
  37. # layoutlmv3
  38. for image in images:
  39. layout_res = self.model.layout_model(image, ignore_catids=[])
  40. images_layout_res.append(layout_res)
  41. elif self.model.layout_model_name == MODEL_NAME.DocLayout_YOLO:
  42. # doclayout_yolo
  43. layout_images = []
  44. for image_index, image in enumerate(images):
  45. layout_images.append(image)
  46. images_layout_res += self.model.layout_model.batch_predict(
  47. # layout_images, self.batch_ratio * YOLO_LAYOUT_BASE_BATCH_SIZE
  48. layout_images, YOLO_LAYOUT_BASE_BATCH_SIZE
  49. )
  50. # logger.info(
  51. # f'layout time: {round(time.time() - layout_start_time, 2)}, image num: {len(images)}'
  52. # )
  53. if self.model.apply_formula:
  54. # 公式检测
  55. mfd_start_time = time.time()
  56. images_mfd_res = self.model.mfd_model.batch_predict(
  57. # images, self.batch_ratio * MFD_BASE_BATCH_SIZE
  58. images, MFD_BASE_BATCH_SIZE
  59. )
  60. # logger.info(
  61. # f'mfd time: {round(time.time() - mfd_start_time, 2)}, image num: {len(images)}'
  62. # )
  63. # 公式识别
  64. mfr_start_time = time.time()
  65. images_formula_list = self.model.mfr_model.batch_predict(
  66. images_mfd_res,
  67. images,
  68. batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,
  69. )
  70. mfr_count = 0
  71. for image_index in range(len(images)):
  72. images_layout_res[image_index] += images_formula_list[image_index]
  73. mfr_count += len(images_formula_list[image_index])
  74. # logger.info(
  75. # f'mfr time: {round(time.time() - mfr_start_time, 2)}, image num: {mfr_count}'
  76. # )
  77. # 清理显存
  78. # clean_vram(self.model.device, vram_threshold=8)
  79. ocr_res_list_all_page = []
  80. table_res_list_all_page = []
  81. for index in range(len(images)):
  82. _, ocr_enable, _lang = images_with_extra_info[index]
  83. layout_res = images_layout_res[index]
  84. np_array_img = images[index]
  85. ocr_res_list, table_res_list, single_page_mfdetrec_res = (
  86. get_res_list_from_layout_res(layout_res)
  87. )
  88. ocr_res_list_all_page.append({'ocr_res_list':ocr_res_list,
  89. 'lang':_lang,
  90. 'ocr_enable':ocr_enable,
  91. 'np_array_img':np_array_img,
  92. 'single_page_mfdetrec_res':single_page_mfdetrec_res,
  93. 'layout_res':layout_res,
  94. })
  95. for table_res in table_res_list:
  96. table_img, _ = crop_img(table_res, np_array_img)
  97. table_res_list_all_page.append({'table_res':table_res,
  98. 'lang':_lang,
  99. 'table_img':table_img,
  100. })
  101. # 文本框检测
  102. det_start = time.time()
  103. det_count = 0
  104. # for ocr_res_list_dict in ocr_res_list_all_page:
  105. for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):
  106. # Process each area that requires OCR processing
  107. _lang = ocr_res_list_dict['lang']
  108. # Get OCR results for this language's images
  109. atom_model_manager = AtomModelSingleton()
  110. ocr_model = atom_model_manager.get_atom_model(
  111. atom_model_name='ocr',
  112. ocr_show_log=False,
  113. det_db_box_thresh=0.3,
  114. lang=_lang
  115. )
  116. for res in ocr_res_list_dict['ocr_res_list']:
  117. new_image, useful_list = crop_img(
  118. res, ocr_res_list_dict['np_array_img'], crop_paste_x=50, crop_paste_y=50
  119. )
  120. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  121. ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
  122. )
  123. # OCR-det
  124. new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
  125. ocr_res = ocr_model.ocr(
  126. new_image, mfd_res=adjusted_mfdetrec_res, rec=False
  127. )[0]
  128. # Integration results
  129. if ocr_res:
  130. ocr_result_list = get_ocr_result_list(ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], new_image, _lang)
  131. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  132. # det_count += len(ocr_res_list_dict['ocr_res_list'])
  133. # logger.info(f'ocr-det time: {round(time.time()-det_start, 2)}, image num: {det_count}')
  134. # 表格识别 table recognition
  135. if self.model.apply_table:
  136. table_start = time.time()
  137. # for table_res_list_dict in table_res_list_all_page:
  138. for table_res_dict in tqdm(table_res_list_all_page, desc="Table Predict"):
  139. _lang = table_res_dict['lang']
  140. atom_model_manager = AtomModelSingleton()
  141. ocr_engine = atom_model_manager.get_atom_model(
  142. atom_model_name='ocr',
  143. ocr_show_log=False,
  144. det_db_box_thresh=0.5,
  145. det_db_unclip_ratio=1.6,
  146. lang=_lang
  147. )
  148. table_model = atom_model_manager.get_atom_model(
  149. atom_model_name='table',
  150. table_model_name='rapid_table',
  151. table_model_path='',
  152. table_max_time=400,
  153. device='cpu',
  154. ocr_engine=ocr_engine,
  155. table_sub_model_name='slanet_plus'
  156. )
  157. html_code, table_cell_bboxes, logic_points, elapse = table_model.predict(table_res_dict['table_img'])
  158. # 判断是否返回正常
  159. if html_code:
  160. expected_ending = html_code.strip().endswith(
  161. '</html>'
  162. ) or html_code.strip().endswith('</table>')
  163. if expected_ending:
  164. table_res_dict['table_res']['html'] = html_code
  165. else:
  166. logger.warning(
  167. 'table recognition processing fails, not found expected HTML table end'
  168. )
  169. else:
  170. logger.warning(
  171. 'table recognition processing fails, not get html return'
  172. )
  173. # logger.info(f'table time: {round(time.time() - table_start, 2)}, image num: {len(table_res_list_all_page)}')
  174. # Create dictionaries to store items by language
  175. need_ocr_lists_by_lang = {} # Dict of lists for each language
  176. img_crop_lists_by_lang = {} # Dict of lists for each language
  177. for layout_res in images_layout_res:
  178. for layout_res_item in layout_res:
  179. if layout_res_item['category_id'] in [15]:
  180. if 'np_img' in layout_res_item and 'lang' in layout_res_item:
  181. lang = layout_res_item['lang']
  182. # Initialize lists for this language if not exist
  183. if lang not in need_ocr_lists_by_lang:
  184. need_ocr_lists_by_lang[lang] = []
  185. img_crop_lists_by_lang[lang] = []
  186. # Add to the appropriate language-specific lists
  187. need_ocr_lists_by_lang[lang].append(layout_res_item)
  188. img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])
  189. # Remove the fields after adding to lists
  190. layout_res_item.pop('np_img')
  191. layout_res_item.pop('lang')
  192. if len(img_crop_lists_by_lang) > 0:
  193. # Process OCR by language
  194. rec_time = 0
  195. rec_start = time.time()
  196. total_processed = 0
  197. # Process each language separately
  198. for lang, img_crop_list in img_crop_lists_by_lang.items():
  199. if len(img_crop_list) > 0:
  200. # Get OCR results for this language's images
  201. atom_model_manager = AtomModelSingleton()
  202. ocr_model = atom_model_manager.get_atom_model(
  203. atom_model_name='ocr',
  204. ocr_show_log=False,
  205. det_db_box_thresh=0.3,
  206. lang=lang
  207. )
  208. ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]
  209. # Verify we have matching counts
  210. assert len(ocr_res_list) == len(
  211. 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}'
  212. # Process OCR results for this language
  213. for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):
  214. ocr_text, ocr_score = ocr_res_list[index]
  215. layout_res_item['text'] = ocr_text
  216. layout_res_item['score'] = float(f"{ocr_score:.3f}")
  217. total_processed += len(img_crop_list)
  218. rec_time += time.time() - rec_start
  219. # logger.info(f'ocr-rec time: {round(rec_time, 2)}, total images processed: {total_processed}')
  220. return images_layout_res