batch_analyze.py 16 KB

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