batch_analyze.py 17 KB

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