batch_analyze.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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, get_coords_and_area)
  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. if res["category_id"] == 3:
  132. # ocr_result_list中所有bbox的面积之和
  133. ocr_res_area = sum(get_coords_and_area(ocr_res_item)[4] for ocr_res_item in ocr_result_list if 'poly' in ocr_res_item)
  134. # 求ocr_res_area和res的面积的比值
  135. res_area = get_coords_and_area(res)[4]
  136. if res_area > 0:
  137. ratio = ocr_res_area / res_area
  138. if ratio > 0.25:
  139. res["category_id"] = 1
  140. else:
  141. continue
  142. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  143. # det_count += len(ocr_res_list_dict['ocr_res_list'])
  144. # logger.info(f'ocr-det time: {round(time.time()-det_start, 2)}, image num: {det_count}')
  145. # 表格识别 table recognition
  146. if self.model.apply_table:
  147. table_start = time.time()
  148. # for table_res_list_dict in table_res_list_all_page:
  149. for table_res_dict in tqdm(table_res_list_all_page, desc="Table Predict"):
  150. _lang = table_res_dict['lang']
  151. atom_model_manager = AtomModelSingleton()
  152. table_model = atom_model_manager.get_atom_model(
  153. atom_model_name='table',
  154. table_model_name='rapid_table',
  155. table_model_path='',
  156. table_max_time=400,
  157. device='cpu',
  158. lang=_lang,
  159. table_sub_model_name='slanet_plus'
  160. )
  161. html_code, table_cell_bboxes, logic_points, elapse = table_model.predict(table_res_dict['table_img'])
  162. # 判断是否返回正常
  163. if html_code:
  164. expected_ending = html_code.strip().endswith(
  165. '</html>'
  166. ) or html_code.strip().endswith('</table>')
  167. if expected_ending:
  168. table_res_dict['table_res']['html'] = html_code
  169. else:
  170. logger.warning(
  171. 'table recognition processing fails, not found expected HTML table end'
  172. )
  173. else:
  174. logger.warning(
  175. 'table recognition processing fails, not get html return'
  176. )
  177. # logger.info(f'table time: {round(time.time() - table_start, 2)}, image num: {len(table_res_list_all_page)}')
  178. # Create dictionaries to store items by language
  179. need_ocr_lists_by_lang = {} # Dict of lists for each language
  180. img_crop_lists_by_lang = {} # Dict of lists for each language
  181. for layout_res in images_layout_res:
  182. for layout_res_item in layout_res:
  183. if layout_res_item['category_id'] in [15]:
  184. if 'np_img' in layout_res_item and 'lang' in layout_res_item:
  185. lang = layout_res_item['lang']
  186. # Initialize lists for this language if not exist
  187. if lang not in need_ocr_lists_by_lang:
  188. need_ocr_lists_by_lang[lang] = []
  189. img_crop_lists_by_lang[lang] = []
  190. # Add to the appropriate language-specific lists
  191. need_ocr_lists_by_lang[lang].append(layout_res_item)
  192. img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])
  193. # Remove the fields after adding to lists
  194. layout_res_item.pop('np_img')
  195. layout_res_item.pop('lang')
  196. if len(img_crop_lists_by_lang) > 0:
  197. # Process OCR by language
  198. rec_time = 0
  199. rec_start = time.time()
  200. total_processed = 0
  201. # Process each language separately
  202. for lang, img_crop_list in img_crop_lists_by_lang.items():
  203. if len(img_crop_list) > 0:
  204. # Get OCR results for this language's images
  205. atom_model_manager = AtomModelSingleton()
  206. ocr_model = atom_model_manager.get_atom_model(
  207. atom_model_name='ocr',
  208. ocr_show_log=False,
  209. det_db_box_thresh=0.3,
  210. lang=lang
  211. )
  212. ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]
  213. # Verify we have matching counts
  214. assert len(ocr_res_list) == len(
  215. 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}'
  216. # Process OCR results for this language
  217. for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):
  218. ocr_text, ocr_score = ocr_res_list[index]
  219. layout_res_item['text'] = ocr_text
  220. layout_res_item['score'] = float(f"{ocr_score:.3f}")
  221. total_processed += len(img_crop_list)
  222. rec_time += time.time() - rec_start
  223. # logger.info(f'ocr-rec time: {round(rec_time, 2)}, total images processed: {total_processed}')
  224. return images_layout_res