batch_analyze.py 21 KB

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