batch_analyze.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import time
  2. import cv2
  3. from loguru import logger
  4. from tqdm import tqdm
  5. from collections import defaultdict
  6. import numpy as np
  7. from magic_pdf.config.constants import MODEL_NAME
  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, get_coords_and_area)
  11. from magic_pdf.model.sub_modules.ocr.paddleocr2pytorch.ocr_utils import (
  12. get_adjusted_mfdetrec_res, get_ocr_result_list)
  13. YOLO_LAYOUT_BASE_BATCH_SIZE = 1
  14. MFD_BASE_BATCH_SIZE = 1
  15. MFR_BASE_BATCH_SIZE = 16
  16. class BatchAnalyze:
  17. def __init__(self, model_manager, batch_ratio: int, show_log, layout_model, formula_enable, table_enable, enable_ocr_det_batch=True):
  18. self.model_manager = model_manager
  19. self.batch_ratio = batch_ratio
  20. self.show_log = show_log
  21. self.layout_model = layout_model
  22. self.formula_enable = formula_enable
  23. self.table_enable = table_enable
  24. self.enable_ocr_det_batch = enable_ocr_det_batch
  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. self.model = self.model_manager.get_model(
  31. ocr=True,
  32. show_log=self.show_log,
  33. lang=None,
  34. layout_model=self.layout_model,
  35. formula_enable=self.formula_enable,
  36. table_enable=self.table_enable,
  37. )
  38. images = [image for image, _, _ in images_with_extra_info]
  39. if self.model.layout_model_name == MODEL_NAME.LAYOUTLMv3:
  40. # layoutlmv3
  41. for image in images:
  42. layout_res = self.model.layout_model(image, ignore_catids=[])
  43. images_layout_res.append(layout_res)
  44. elif self.model.layout_model_name == MODEL_NAME.DocLayout_YOLO:
  45. # doclayout_yolo
  46. layout_images = []
  47. for image_index, image in enumerate(images):
  48. layout_images.append(image)
  49. images_layout_res += self.model.layout_model.batch_predict(
  50. # layout_images, self.batch_ratio * YOLO_LAYOUT_BASE_BATCH_SIZE
  51. layout_images, YOLO_LAYOUT_BASE_BATCH_SIZE
  52. )
  53. # logger.info(
  54. # f'layout time: {round(time.time() - layout_start_time, 2)}, image num: {len(images)}'
  55. # )
  56. if self.model.apply_formula:
  57. # 公式检测
  58. mfd_start_time = time.time()
  59. images_mfd_res = self.model.mfd_model.batch_predict(
  60. # images, self.batch_ratio * MFD_BASE_BATCH_SIZE
  61. images, MFD_BASE_BATCH_SIZE
  62. )
  63. # logger.info(
  64. # f'mfd time: {round(time.time() - mfd_start_time, 2)}, image num: {len(images)}'
  65. # )
  66. # 公式识别
  67. mfr_start_time = time.time()
  68. images_formula_list = self.model.mfr_model.batch_predict(
  69. images_mfd_res,
  70. images,
  71. batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,
  72. )
  73. mfr_count = 0
  74. for image_index in range(len(images)):
  75. images_layout_res[image_index] += images_formula_list[image_index]
  76. mfr_count += len(images_formula_list[image_index])
  77. # logger.info(
  78. # f'mfr time: {round(time.time() - mfr_start_time, 2)}, image num: {mfr_count}'
  79. # )
  80. # 清理显存
  81. # clean_vram(self.model.device, vram_threshold=8)
  82. ocr_res_list_all_page = []
  83. table_res_list_all_page = []
  84. for index in range(len(images)):
  85. _, ocr_enable, _lang = images_with_extra_info[index]
  86. layout_res = images_layout_res[index]
  87. np_array_img = images[index]
  88. ocr_res_list, table_res_list, single_page_mfdetrec_res = (
  89. get_res_list_from_layout_res(layout_res)
  90. )
  91. ocr_res_list_all_page.append({
  92. 'ocr_res_list': ocr_res_list,
  93. 'lang': _lang,
  94. 'ocr_enable': ocr_enable,
  95. 'np_array_img': np_array_img,
  96. 'single_page_mfdetrec_res': single_page_mfdetrec_res,
  97. 'layout_res': layout_res,
  98. })
  99. for table_res in table_res_list:
  100. table_img, _ = crop_img(table_res, np_array_img)
  101. table_res_list_all_page.append({
  102. 'table_res': table_res,
  103. 'lang': _lang,
  104. 'table_img': table_img,
  105. })
  106. # OCR检测处理
  107. if self.enable_ocr_det_batch:
  108. # 批处理模式 - 按语言和分辨率分组
  109. # 收集所有需要OCR检测的裁剪图像
  110. all_cropped_images_info = []
  111. for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="Preparing OCR-det batches"):
  112. _lang = ocr_res_list_dict['lang']
  113. for res in ocr_res_list_dict['ocr_res_list']:
  114. new_image, useful_list = crop_img(
  115. res, ocr_res_list_dict['np_array_img'], crop_paste_x=50, crop_paste_y=50
  116. )
  117. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  118. ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
  119. )
  120. # BGR转换
  121. new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
  122. all_cropped_images_info.append((
  123. new_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang
  124. ))
  125. # 按语言分组
  126. lang_groups = defaultdict(list)
  127. for crop_info in all_cropped_images_info:
  128. lang = crop_info[5]
  129. lang_groups[lang].append(crop_info)
  130. # 对每种语言按分辨率分组并批处理
  131. for lang, lang_crop_list in lang_groups.items():
  132. if not lang_crop_list:
  133. continue
  134. logger.info(f"Processing OCR detection for language {lang} with {len(lang_crop_list)} images")
  135. # 获取OCR模型
  136. atom_model_manager = AtomModelSingleton()
  137. ocr_model = atom_model_manager.get_atom_model(
  138. atom_model_name='ocr',
  139. ocr_show_log=False,
  140. det_db_box_thresh=0.3,
  141. lang=lang
  142. )
  143. # 按分辨率分组并同时完成padding
  144. resolution_groups = defaultdict(list)
  145. for crop_info in lang_crop_list:
  146. cropped_img = crop_info[0]
  147. h, w = cropped_img.shape[:2]
  148. # 使用更大的分组容差,减少分组数量
  149. # 将尺寸标准化到32的倍数
  150. normalized_h = ((h + 32) // 32) * 32 # 向上取整到32的倍数
  151. normalized_w = ((w + 32) // 32) * 32
  152. group_key = (normalized_h, normalized_w)
  153. resolution_groups[group_key].append(crop_info)
  154. # 对每个分辨率组进行批处理
  155. for group_key, group_crops in tqdm(resolution_groups.items(), desc=f"OCR-det {lang}"):
  156. raw_images = [crop_info[0] for crop_info in group_crops]
  157. # 计算目标尺寸(组内最大尺寸,向上取整到32的倍数)
  158. max_h = max(img.shape[0] for img in raw_images)
  159. max_w = max(img.shape[1] for img in raw_images)
  160. target_h = ((max_h + 32 - 1) // 32) * 32
  161. target_w = ((max_w + 32 - 1) // 32) * 32
  162. # 对所有图像进行padding到统一尺寸
  163. batch_images = []
  164. for img in raw_images:
  165. h, w = img.shape[:2]
  166. # 创建目标尺寸的白色背景
  167. padded_img = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
  168. # 将原图像粘贴到左上角
  169. padded_img[:h, :w] = img
  170. batch_images.append(padded_img)
  171. # 批处理检测
  172. batch_size = min(len(batch_images), self.batch_ratio * 16) # 增加批处理大小
  173. logger.debug(f"OCR-det batch: {batch_size} images, target size: {target_h}x{target_w}")
  174. batch_results = ocr_model.text_detector.batch_predict(batch_images, batch_size)
  175. # 处理批处理结果
  176. for i, (crop_info, (dt_boxes, elapse)) in enumerate(zip(group_crops, batch_results)):
  177. new_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang = crop_info
  178. if dt_boxes is not None:
  179. # 构造OCR结果格式 - 每个box应该是4个点的列表
  180. ocr_res = [box.tolist() for box in dt_boxes]
  181. if ocr_res:
  182. ocr_result_list = get_ocr_result_list(
  183. ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], new_image, _lang
  184. )
  185. if res["category_id"] == 3:
  186. # ocr_result_list中所有bbox的面积之和
  187. 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)
  188. # 求ocr_res_area和res的面积的比值
  189. res_area = get_coords_and_area(res)[4]
  190. if res_area > 0:
  191. ratio = ocr_res_area / res_area
  192. if ratio > 0.25:
  193. res["category_id"] = 1
  194. else:
  195. continue
  196. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  197. else:
  198. # 原始单张处理模式
  199. for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):
  200. # Process each area that requires OCR processing
  201. _lang = ocr_res_list_dict['lang']
  202. # Get OCR results for this language's images
  203. atom_model_manager = AtomModelSingleton()
  204. ocr_model = atom_model_manager.get_atom_model(
  205. atom_model_name='ocr',
  206. ocr_show_log=False,
  207. det_db_box_thresh=0.3,
  208. lang=_lang
  209. )
  210. for res in ocr_res_list_dict['ocr_res_list']:
  211. new_image, useful_list = crop_img(
  212. res, ocr_res_list_dict['np_array_img'], crop_paste_x=50, crop_paste_y=50
  213. )
  214. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  215. ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
  216. )
  217. # OCR-det
  218. new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
  219. ocr_res = ocr_model.ocr(
  220. new_image, mfd_res=adjusted_mfdetrec_res, rec=False
  221. )[0]
  222. # Integration results
  223. if ocr_res:
  224. ocr_result_list = get_ocr_result_list(ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], new_image, _lang)
  225. if res["category_id"] == 3:
  226. # ocr_result_list中所有bbox的面积之和
  227. 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)
  228. # 求ocr_res_area和res的面积的比值
  229. res_area = get_coords_and_area(res)[4]
  230. if res_area > 0:
  231. ratio = ocr_res_area / res_area
  232. if ratio > 0.25:
  233. res["category_id"] = 1
  234. else:
  235. continue
  236. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  237. # det_count += len(ocr_res_list_dict['ocr_res_list'])
  238. # logger.info(f'ocr-det time: {round(time.time()-det_start, 2)}, image num: {det_count}')
  239. # 表格识别 table recognition
  240. if self.model.apply_table:
  241. table_start = time.time()
  242. # for table_res_list_dict in table_res_list_all_page:
  243. for table_res_dict in tqdm(table_res_list_all_page, desc="Table Predict"):
  244. _lang = table_res_dict['lang']
  245. atom_model_manager = AtomModelSingleton()
  246. table_model = atom_model_manager.get_atom_model(
  247. atom_model_name='table',
  248. table_model_name='rapid_table',
  249. table_model_path='',
  250. table_max_time=400,
  251. device='cpu',
  252. lang=_lang,
  253. table_sub_model_name='slanet_plus'
  254. )
  255. html_code, table_cell_bboxes, logic_points, elapse = table_model.predict(table_res_dict['table_img'])
  256. # 判断是否返回正常
  257. if html_code:
  258. expected_ending = html_code.strip().endswith(
  259. '</html>'
  260. ) or html_code.strip().endswith('</table>')
  261. if expected_ending:
  262. table_res_dict['table_res']['html'] = html_code
  263. else:
  264. logger.warning(
  265. 'table recognition processing fails, not found expected HTML table end'
  266. )
  267. else:
  268. logger.warning(
  269. 'table recognition processing fails, not get html return'
  270. )
  271. # logger.info(f'table time: {round(time.time() - table_start, 2)}, image num: {len(table_res_list_all_page)}')
  272. # Create dictionaries to store items by language
  273. need_ocr_lists_by_lang = {} # Dict of lists for each language
  274. img_crop_lists_by_lang = {} # Dict of lists for each language
  275. for layout_res in images_layout_res:
  276. for layout_res_item in layout_res:
  277. if layout_res_item['category_id'] in [15]:
  278. if 'np_img' in layout_res_item and 'lang' in layout_res_item:
  279. lang = layout_res_item['lang']
  280. # Initialize lists for this language if not exist
  281. if lang not in need_ocr_lists_by_lang:
  282. need_ocr_lists_by_lang[lang] = []
  283. img_crop_lists_by_lang[lang] = []
  284. # Add to the appropriate language-specific lists
  285. need_ocr_lists_by_lang[lang].append(layout_res_item)
  286. img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])
  287. # Remove the fields after adding to lists
  288. layout_res_item.pop('np_img')
  289. layout_res_item.pop('lang')
  290. if len(img_crop_lists_by_lang) > 0:
  291. # Process OCR by language
  292. rec_time = 0
  293. rec_start = time.time()
  294. total_processed = 0
  295. # Process each language separately
  296. for lang, img_crop_list in img_crop_lists_by_lang.items():
  297. if len(img_crop_list) > 0:
  298. # Get OCR results for this language's images
  299. atom_model_manager = AtomModelSingleton()
  300. ocr_model = atom_model_manager.get_atom_model(
  301. atom_model_name='ocr',
  302. ocr_show_log=False,
  303. det_db_box_thresh=0.3,
  304. lang=lang
  305. )
  306. ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]
  307. # Verify we have matching counts
  308. assert len(ocr_res_list) == len(
  309. 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}'
  310. # Process OCR results for this language
  311. for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):
  312. ocr_text, ocr_score = ocr_res_list[index]
  313. layout_res_item['text'] = ocr_text
  314. layout_res_item['score'] = float(f"{ocr_score:.3f}")
  315. total_processed += len(img_crop_list)
  316. rec_time += time.time() - rec_start
  317. # logger.info(f'ocr-rec time: {round(rec_time, 2)}, total images processed: {total_processed}')
  318. return images_layout_res