batch_analyze.py 15 KB

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