batch_analyze.py 20 KB

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