batch_analyze.py 21 KB

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