batch_analyze.py 20 KB

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