batch_analyze.py 17 KB

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