batch_analyze.py 17 KB

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