batch_analyze.py 11 KB

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