batch_analyze.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import cv2
  2. from loguru import logger
  3. from tqdm import tqdm
  4. from collections import defaultdict
  5. import numpy as np
  6. from .model_init import AtomModelSingleton
  7. from ...utils.config_reader import get_formula_enable, get_table_enable
  8. from ...utils.model_utils import crop_img, get_res_list_from_layout_res
  9. from ...utils.ocr_utils import get_adjusted_mfdetrec_res, get_ocr_result_list, OcrConfidence
  10. YOLO_LAYOUT_BASE_BATCH_SIZE = 8
  11. MFD_BASE_BATCH_SIZE = 1
  12. MFR_BASE_BATCH_SIZE = 16
  13. class BatchAnalyze:
  14. def __init__(self, model_manager, batch_ratio: int, formula_enable, table_enable, enable_ocr_det_batch: bool = True):
  15. self.batch_ratio = batch_ratio
  16. self.formula_enable = get_formula_enable(formula_enable)
  17. self.table_enable = get_table_enable(table_enable)
  18. self.model_manager = model_manager
  19. self.enable_ocr_det_batch = enable_ocr_det_batch
  20. def __call__(self, images_with_extra_info: list) -> list:
  21. if len(images_with_extra_info) == 0:
  22. return []
  23. images_layout_res = []
  24. self.model = self.model_manager.get_model(
  25. lang=None,
  26. formula_enable=self.formula_enable,
  27. table_enable=self.table_enable,
  28. )
  29. atom_model_manager = AtomModelSingleton()
  30. images = [image for image, _, _ in images_with_extra_info]
  31. # doclayout_yolo
  32. layout_images = []
  33. for image_index, image in enumerate(images):
  34. layout_images.append(image)
  35. images_layout_res += self.model.layout_model.batch_predict(
  36. layout_images, YOLO_LAYOUT_BASE_BATCH_SIZE
  37. )
  38. if self.formula_enable:
  39. # 公式检测
  40. images_mfd_res = self.model.mfd_model.batch_predict(
  41. images, MFD_BASE_BATCH_SIZE
  42. )
  43. # 公式识别
  44. images_formula_list = self.model.mfr_model.batch_predict(
  45. images_mfd_res,
  46. images,
  47. batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,
  48. )
  49. mfr_count = 0
  50. for image_index in range(len(images)):
  51. images_layout_res[image_index] += images_formula_list[image_index]
  52. mfr_count += len(images_formula_list[image_index])
  53. # 清理显存
  54. # clean_vram(self.model.device, vram_threshold=8)
  55. ocr_res_list_all_page = []
  56. table_res_list_all_page = []
  57. for index in range(len(images)):
  58. _, ocr_enable, _lang = images_with_extra_info[index]
  59. layout_res = images_layout_res[index]
  60. pil_img = images[index]
  61. ocr_res_list, table_res_list, single_page_mfdetrec_res = (
  62. get_res_list_from_layout_res(layout_res)
  63. )
  64. ocr_res_list_all_page.append({'ocr_res_list':ocr_res_list,
  65. 'lang':_lang,
  66. 'ocr_enable':ocr_enable,
  67. 'pil_img':pil_img,
  68. 'single_page_mfdetrec_res':single_page_mfdetrec_res,
  69. 'layout_res':layout_res,
  70. })
  71. for table_res in table_res_list:
  72. table_img, _ = crop_img(table_res, pil_img)
  73. table_res_list_all_page.append({'table_res':table_res,
  74. 'lang':_lang,
  75. 'table_img':table_img,
  76. })
  77. # OCR检测处理
  78. if self.enable_ocr_det_batch:
  79. # 批处理模式 - 按语言和分辨率分组
  80. # 收集所有需要OCR检测的裁剪图像
  81. all_cropped_images_info = []
  82. for ocr_res_list_dict in ocr_res_list_all_page:
  83. _lang = ocr_res_list_dict['lang']
  84. for res in ocr_res_list_dict['ocr_res_list']:
  85. new_image, useful_list = crop_img(
  86. res, ocr_res_list_dict['pil_img'], crop_paste_x=50, crop_paste_y=50
  87. )
  88. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  89. ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
  90. )
  91. # BGR转换
  92. new_image = cv2.cvtColor(np.asarray(new_image), cv2.COLOR_RGB2BGR)
  93. all_cropped_images_info.append((
  94. new_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang
  95. ))
  96. # 按语言分组
  97. lang_groups = defaultdict(list)
  98. for crop_info in all_cropped_images_info:
  99. lang = crop_info[5]
  100. lang_groups[lang].append(crop_info)
  101. # 对每种语言按分辨率分组并批处理
  102. for lang, lang_crop_list in lang_groups.items():
  103. if not lang_crop_list:
  104. continue
  105. # logger.info(f"Processing OCR detection for language {lang} with {len(lang_crop_list)} images")
  106. # 获取OCR模型
  107. ocr_model = atom_model_manager.get_atom_model(
  108. atom_model_name='ocr',
  109. det_db_box_thresh=0.3,
  110. lang=lang
  111. )
  112. # 按分辨率分组并同时完成padding
  113. resolution_groups = defaultdict(list)
  114. for crop_info in lang_crop_list:
  115. cropped_img = crop_info[0]
  116. h, w = cropped_img.shape[:2]
  117. # 使用更大的分组容差,减少分组数量
  118. # 将尺寸标准化到32的倍数
  119. normalized_h = ((h + 32) // 32) * 32 # 向上取整到32的倍数
  120. normalized_w = ((w + 32) // 32) * 32
  121. group_key = (normalized_h, normalized_w)
  122. resolution_groups[group_key].append(crop_info)
  123. # 对每个分辨率组进行批处理
  124. for group_key, group_crops in tqdm(resolution_groups.items(), desc=f"OCR-det {lang}"):
  125. # 计算目标尺寸(组内最大尺寸,向上取整到32的倍数)
  126. max_h = max(crop_info[0].shape[0] for crop_info in group_crops)
  127. max_w = max(crop_info[0].shape[1] for crop_info in group_crops)
  128. target_h = ((max_h + 32 - 1) // 32) * 32
  129. target_w = ((max_w + 32 - 1) // 32) * 32
  130. # 对所有图像进行padding到统一尺寸
  131. batch_images = []
  132. for crop_info in group_crops:
  133. img = crop_info[0]
  134. h, w = img.shape[:2]
  135. # 创建目标尺寸的白色背景
  136. padded_img = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
  137. # 将原图像粘贴到左上角
  138. padded_img[:h, :w] = img
  139. batch_images.append(padded_img)
  140. # 批处理检测
  141. batch_size = min(len(batch_images), self.batch_ratio * 16) # 增加批处理大小
  142. # logger.debug(f"OCR-det batch: {batch_size} images, target size: {target_h}x{target_w}")
  143. batch_results = ocr_model.text_detector.batch_predict(batch_images, batch_size)
  144. # 处理批处理结果
  145. for i, (crop_info, (dt_boxes, elapse)) in enumerate(zip(group_crops, batch_results)):
  146. new_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang = crop_info
  147. if dt_boxes is not None and len(dt_boxes) > 0:
  148. # 直接应用原始OCR流程中的关键处理步骤
  149. from mineru.utils.ocr_utils import (
  150. merge_det_boxes, update_det_boxes, sorted_boxes
  151. )
  152. # 1. 排序检测框
  153. if len(dt_boxes) > 0:
  154. dt_boxes_sorted = sorted_boxes(dt_boxes)
  155. else:
  156. dt_boxes_sorted = []
  157. # 2. 合并相邻检测框
  158. if dt_boxes_sorted:
  159. dt_boxes_merged = merge_det_boxes(dt_boxes_sorted)
  160. else:
  161. dt_boxes_merged = []
  162. # 3. 根据公式位置更新检测框(关键步骤!)
  163. if dt_boxes_merged and adjusted_mfdetrec_res:
  164. dt_boxes_final = update_det_boxes(dt_boxes_merged, adjusted_mfdetrec_res)
  165. else:
  166. dt_boxes_final = dt_boxes_merged
  167. # 构造OCR结果格式
  168. ocr_res = [box.tolist() if hasattr(box, 'tolist') else box for box in dt_boxes_final]
  169. if ocr_res:
  170. ocr_result_list = get_ocr_result_list(
  171. ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], new_image, _lang
  172. )
  173. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  174. else:
  175. # 原始单张处理模式
  176. for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):
  177. # Process each area that requires OCR processing
  178. _lang = ocr_res_list_dict['lang']
  179. # Get OCR results for this language's images
  180. ocr_model = atom_model_manager.get_atom_model(
  181. atom_model_name='ocr',
  182. ocr_show_log=False,
  183. det_db_box_thresh=0.3,
  184. lang=_lang
  185. )
  186. for res in ocr_res_list_dict['ocr_res_list']:
  187. new_image, useful_list = crop_img(
  188. res, ocr_res_list_dict['pil_img'], crop_paste_x=50, crop_paste_y=50
  189. )
  190. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  191. ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
  192. )
  193. # OCR-det
  194. new_image = cv2.cvtColor(np.asarray(new_image), cv2.COLOR_RGB2BGR)
  195. ocr_res = ocr_model.ocr(
  196. new_image, mfd_res=adjusted_mfdetrec_res, rec=False
  197. )[0]
  198. # Integration results
  199. if ocr_res:
  200. ocr_result_list = get_ocr_result_list(
  201. ocr_res, useful_list, ocr_res_list_dict['ocr_enable'],new_image, _lang
  202. )
  203. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  204. # 表格识别 table recognition
  205. if self.table_enable:
  206. for table_res_dict in tqdm(table_res_list_all_page, desc="Table Predict"):
  207. _lang = table_res_dict['lang']
  208. table_model = atom_model_manager.get_atom_model(
  209. atom_model_name='table',
  210. lang=_lang,
  211. )
  212. html_code, table_cell_bboxes, logic_points, elapse = table_model.predict(table_res_dict['table_img'])
  213. # 判断是否返回正常
  214. if html_code:
  215. expected_ending = html_code.strip().endswith('</html>') or html_code.strip().endswith('</table>')
  216. if expected_ending:
  217. table_res_dict['table_res']['html'] = html_code
  218. else:
  219. logger.warning(
  220. 'table recognition processing fails, not found expected HTML table end'
  221. )
  222. else:
  223. logger.warning(
  224. 'table recognition processing fails, not get html return'
  225. )
  226. # Create dictionaries to store items by language
  227. need_ocr_lists_by_lang = {} # Dict of lists for each language
  228. img_crop_lists_by_lang = {} # Dict of lists for each language
  229. for layout_res in images_layout_res:
  230. for layout_res_item in layout_res:
  231. if layout_res_item['category_id'] in [15]:
  232. if 'np_img' in layout_res_item and 'lang' in layout_res_item:
  233. lang = layout_res_item['lang']
  234. # Initialize lists for this language if not exist
  235. if lang not in need_ocr_lists_by_lang:
  236. need_ocr_lists_by_lang[lang] = []
  237. img_crop_lists_by_lang[lang] = []
  238. # Add to the appropriate language-specific lists
  239. need_ocr_lists_by_lang[lang].append(layout_res_item)
  240. img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])
  241. # Remove the fields after adding to lists
  242. layout_res_item.pop('np_img')
  243. layout_res_item.pop('lang')
  244. if len(img_crop_lists_by_lang) > 0:
  245. # Process OCR by language
  246. total_processed = 0
  247. # Process each language separately
  248. for lang, img_crop_list in img_crop_lists_by_lang.items():
  249. if len(img_crop_list) > 0:
  250. # Get OCR results for this language's images
  251. ocr_model = atom_model_manager.get_atom_model(
  252. atom_model_name='ocr',
  253. det_db_box_thresh=0.3,
  254. lang=lang
  255. )
  256. ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]
  257. # Verify we have matching counts
  258. assert len(ocr_res_list) == len(
  259. 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}'
  260. # Process OCR results for this language
  261. for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):
  262. ocr_text, ocr_score = ocr_res_list[index]
  263. layout_res_item['text'] = ocr_text
  264. layout_res_item['score'] = float(f"{ocr_score:.3f}")
  265. if ocr_score < OcrConfidence.min_confidence:
  266. layout_res_item['category_id'] = 16
  267. else:
  268. layout_res_bbox = [layout_res_item['poly'][0], layout_res_item['poly'][1],
  269. layout_res_item['poly'][4], layout_res_item['poly'][5]]
  270. layout_res_width = layout_res_bbox[2] - layout_res_bbox[0]
  271. layout_res_height = layout_res_bbox[3] - layout_res_bbox[1]
  272. if ocr_text in ['(204号', '(20', '(2', '(2号', '(20号'] and ocr_score < 0.8 and layout_res_width < layout_res_height:
  273. layout_res_item['category_id'] = 16
  274. total_processed += len(img_crop_list)
  275. return images_layout_res