batch_analyze.py 18 KB

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