batch_analyze.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 = False):
  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. pil_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. 'pil_img':pil_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, pil_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['pil_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(np.asarray(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. det_db_box_thresh=0.3,
  109. lang=lang
  110. )
  111. # 按分辨率分组并同时完成padding
  112. resolution_groups = defaultdict(list)
  113. for crop_info in lang_crop_list:
  114. cropped_img = crop_info[0]
  115. h, w = cropped_img.shape[:2]
  116. # 使用更大的分组容差,减少分组数量
  117. # 将尺寸标准化到32的倍数
  118. normalized_h = ((h + 32) // 32) * 32 # 向上取整到32的倍数
  119. normalized_w = ((w + 32) // 32) * 32
  120. group_key = (normalized_h, normalized_w)
  121. resolution_groups[group_key].append(crop_info)
  122. # 对每个分辨率组进行批处理
  123. for group_key, group_crops in tqdm(resolution_groups.items(), desc=f"OCR-det {lang}"):
  124. raw_images = [crop_info[0] for crop_info in group_crops]
  125. # 计算目标尺寸(组内最大尺寸,向上取整到32的倍数)
  126. max_h = max(img.shape[0] for img in raw_images)
  127. max_w = max(img.shape[1] for img in raw_images)
  128. target_h = ((max_h + 32 - 1) // 32) * 32
  129. target_w = ((max_w + 32 - 1) // 32) * 32
  130. # 对所有图像进行padding到统一尺寸
  131. batch_images = []
  132. for img in raw_images:
  133. h, w = img.shape[:2]
  134. # 创建目标尺寸的白色背景
  135. padded_img = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
  136. # 将原图像粘贴到左上角
  137. padded_img[:h, :w] = img
  138. batch_images.append(padded_img)
  139. # 批处理检测
  140. batch_size = min(len(batch_images), self.batch_ratio * 16) # 增加批处理大小
  141. # logger.debug(f"OCR-det batch: {batch_size} images, target size: {target_h}x{target_w}")
  142. batch_results = ocr_model.text_detector.batch_predict(batch_images, batch_size)
  143. # 处理批处理结果
  144. for i, (crop_info, (dt_boxes, elapse)) in enumerate(zip(group_crops, batch_results)):
  145. new_image, useful_list, ocr_res_list_dict, res, adjusted_mfdetrec_res, _lang = crop_info
  146. if dt_boxes is not None:
  147. # 构造OCR结果格式 - 每个box应该是4个点的列表
  148. ocr_res = [box.tolist() for box in dt_boxes]
  149. if ocr_res:
  150. ocr_result_list = get_ocr_result_list(
  151. ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], new_image, _lang
  152. )
  153. if res["category_id"] == 3:
  154. # ocr_result_list中所有bbox的面积之和
  155. ocr_res_area = sum(
  156. get_coords_and_area(ocr_res_item)[4] for ocr_res_item in ocr_result_list if 'poly' in ocr_res_item)
  157. # 求ocr_res_area和res的面积的比值
  158. res_area = get_coords_and_area(res)[4]
  159. if res_area > 0:
  160. ratio = ocr_res_area / res_area
  161. if ratio > 0.25:
  162. res["category_id"] = 1
  163. else:
  164. continue
  165. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  166. else:
  167. # 原始单张处理模式
  168. for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):
  169. # Process each area that requires OCR processing
  170. _lang = ocr_res_list_dict['lang']
  171. # Get OCR results for this language's images
  172. ocr_model = atom_model_manager.get_atom_model(
  173. atom_model_name='ocr',
  174. ocr_show_log=False,
  175. det_db_box_thresh=0.3,
  176. lang=_lang
  177. )
  178. for res in ocr_res_list_dict['ocr_res_list']:
  179. new_image, useful_list = crop_img(
  180. res, ocr_res_list_dict['pil_img'], crop_paste_x=50, crop_paste_y=50
  181. )
  182. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  183. ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
  184. )
  185. # OCR-det
  186. new_image = cv2.cvtColor(np.asarray(new_image), cv2.COLOR_RGB2BGR)
  187. ocr_res = ocr_model.ocr(
  188. new_image, mfd_res=adjusted_mfdetrec_res, rec=False
  189. )[0]
  190. # Integration results
  191. if ocr_res:
  192. ocr_result_list = get_ocr_result_list(ocr_res, useful_list, ocr_res_list_dict['ocr_enable'],
  193. new_image, _lang)
  194. if res["category_id"] == 3:
  195. # ocr_result_list中所有bbox的面积之和
  196. ocr_res_area = sum(
  197. get_coords_and_area(ocr_res_item)[4] for ocr_res_item in ocr_result_list if 'poly' in ocr_res_item)
  198. # 求ocr_res_area和res的面积的比值
  199. res_area = get_coords_and_area(res)[4]
  200. if res_area > 0:
  201. ratio = ocr_res_area / res_area
  202. if ratio > 0.25:
  203. res["category_id"] = 1
  204. else:
  205. continue
  206. ocr_res_list_dict['layout_res'].extend(ocr_result_list)
  207. # 表格识别 table recognition
  208. if self.table_enable:
  209. for table_res_dict in tqdm(table_res_list_all_page, desc="Table Predict"):
  210. _lang = table_res_dict['lang']
  211. table_model = atom_model_manager.get_atom_model(
  212. atom_model_name='table',
  213. device='cpu',
  214. lang=_lang,
  215. table_sub_model_name='slanet_plus'
  216. )
  217. html_code, table_cell_bboxes, logic_points, elapse = table_model.predict(table_res_dict['table_img'])
  218. # 判断是否返回正常
  219. if html_code:
  220. expected_ending = html_code.strip().endswith(
  221. '</html>'
  222. ) or html_code.strip().endswith('</table>')
  223. if expected_ending:
  224. table_res_dict['table_res']['html'] = html_code
  225. else:
  226. logger.warning(
  227. 'table recognition processing fails, not found expected HTML table end'
  228. )
  229. else:
  230. logger.warning(
  231. 'table recognition processing fails, not get html return'
  232. )
  233. # Create dictionaries to store items by language
  234. need_ocr_lists_by_lang = {} # Dict of lists for each language
  235. img_crop_lists_by_lang = {} # Dict of lists for each language
  236. for layout_res in images_layout_res:
  237. for layout_res_item in layout_res:
  238. if layout_res_item['category_id'] in [15]:
  239. if 'np_img' in layout_res_item and 'lang' in layout_res_item:
  240. lang = layout_res_item['lang']
  241. # Initialize lists for this language if not exist
  242. if lang not in need_ocr_lists_by_lang:
  243. need_ocr_lists_by_lang[lang] = []
  244. img_crop_lists_by_lang[lang] = []
  245. # Add to the appropriate language-specific lists
  246. need_ocr_lists_by_lang[lang].append(layout_res_item)
  247. img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])
  248. # Remove the fields after adding to lists
  249. layout_res_item.pop('np_img')
  250. layout_res_item.pop('lang')
  251. if len(img_crop_lists_by_lang) > 0:
  252. # Process OCR by language
  253. total_processed = 0
  254. # Process each language separately
  255. for lang, img_crop_list in img_crop_lists_by_lang.items():
  256. if len(img_crop_list) > 0:
  257. # Get OCR results for this language's images
  258. ocr_model = atom_model_manager.get_atom_model(
  259. atom_model_name='ocr',
  260. det_db_box_thresh=0.3,
  261. lang=lang
  262. )
  263. ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]
  264. # Verify we have matching counts
  265. assert len(ocr_res_list) == len(
  266. 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}'
  267. # Process OCR results for this language
  268. for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):
  269. ocr_text, ocr_score = ocr_res_list[index]
  270. layout_res_item['text'] = ocr_text
  271. layout_res_item['score'] = float(f"{ocr_score:.3f}")
  272. total_processed += len(img_crop_list)
  273. return images_layout_res