batch_analyze.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import time
  2. import cv2
  3. import numpy as np
  4. import torch
  5. from loguru import logger
  6. from PIL import Image
  7. from magic_pdf.config.constants import MODEL_NAME
  8. from magic_pdf.config.exceptions import CUDA_NOT_AVAILABLE
  9. from magic_pdf.data.dataset import Dataset
  10. from magic_pdf.libs.clean_memory import clean_memory
  11. from magic_pdf.model.doc_analyze_by_custom_model import ModelSingleton
  12. from magic_pdf.model.pdf_extract_kit import CustomPEKModel
  13. from magic_pdf.model.sub_modules.model_utils import (
  14. clean_vram, crop_img, get_res_list_from_layout_res)
  15. from magic_pdf.model.sub_modules.ocr.paddleocr.ocr_utils import (
  16. get_adjusted_mfdetrec_res, get_ocr_result_list)
  17. from magic_pdf.operators.models import InferenceResult
  18. YOLO_LAYOUT_BASE_BATCH_SIZE = 4
  19. MFD_BASE_BATCH_SIZE = 1
  20. MFR_BASE_BATCH_SIZE = 16
  21. class BatchAnalyze:
  22. def __init__(self, model: CustomPEKModel, batch_ratio: int):
  23. self.model = model
  24. self.batch_ratio = batch_ratio
  25. def __call__(self, images: list) -> list:
  26. images_layout_res = []
  27. layout_start_time = time.time()
  28. if self.model.layout_model_name == MODEL_NAME.LAYOUTLMv3:
  29. # layoutlmv3
  30. for image in images:
  31. layout_res = self.model.layout_model(image, ignore_catids=[])
  32. images_layout_res.append(layout_res)
  33. elif self.model.layout_model_name == MODEL_NAME.DocLayout_YOLO:
  34. # doclayout_yolo
  35. layout_images = []
  36. modified_images = []
  37. for image_index, image in enumerate(images):
  38. pil_img = Image.fromarray(image)
  39. width, height = pil_img.size
  40. if height > width:
  41. input_res = {'poly': [0, 0, width, 0, width, height, 0, height]}
  42. new_image, useful_list = crop_img(
  43. input_res, pil_img, crop_paste_x=width // 2, crop_paste_y=0
  44. )
  45. layout_images.append(new_image)
  46. modified_images.append([image_index, useful_list])
  47. else:
  48. layout_images.append(pil_img)
  49. images_layout_res += self.model.layout_model.batch_predict(
  50. layout_images, self.batch_ratio * YOLO_LAYOUT_BASE_BATCH_SIZE
  51. )
  52. for image_index, useful_list in modified_images:
  53. for res in images_layout_res[image_index]:
  54. for i in range(len(res['poly'])):
  55. if i % 2 == 0:
  56. res['poly'][i] = (
  57. res['poly'][i] - useful_list[0] + useful_list[2]
  58. )
  59. else:
  60. res['poly'][i] = (
  61. res['poly'][i] - useful_list[1] + useful_list[3]
  62. )
  63. logger.info(
  64. f'layout time: {round(time.time() - layout_start_time, 2)}, image num: {len(images)}'
  65. )
  66. if self.model.apply_formula:
  67. # 公式检测
  68. mfd_start_time = time.time()
  69. images_mfd_res = self.model.mfd_model.batch_predict(
  70. images, self.batch_ratio * MFD_BASE_BATCH_SIZE
  71. )
  72. logger.info(
  73. f'mfd time: {round(time.time() - mfd_start_time, 2)}, image num: {len(images)}'
  74. )
  75. # 公式识别
  76. mfr_start_time = time.time()
  77. images_formula_list = self.model.mfr_model.batch_predict(
  78. images_mfd_res,
  79. images,
  80. batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,
  81. )
  82. for image_index in range(len(images)):
  83. images_layout_res[image_index] += images_formula_list[image_index]
  84. logger.info(
  85. f'mfr time: {round(time.time() - mfr_start_time, 2)}, image num: {len(images)}'
  86. )
  87. # 清理显存
  88. clean_vram(self.model.device, vram_threshold=8)
  89. ocr_time = 0
  90. ocr_count = 0
  91. table_time = 0
  92. table_count = 0
  93. # reference: magic_pdf/model/doc_analyze_by_custom_model.py:doc_analyze
  94. for index in range(len(images)):
  95. layout_res = images_layout_res[index]
  96. pil_img = Image.fromarray(images[index])
  97. ocr_res_list, table_res_list, single_page_mfdetrec_res = (
  98. get_res_list_from_layout_res(layout_res)
  99. )
  100. # ocr识别
  101. ocr_start = time.time()
  102. # Process each area that requires OCR processing
  103. for res in ocr_res_list:
  104. new_image, useful_list = crop_img(
  105. res, pil_img, crop_paste_x=50, crop_paste_y=50
  106. )
  107. adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
  108. single_page_mfdetrec_res, useful_list
  109. )
  110. # OCR recognition
  111. new_image = cv2.cvtColor(np.asarray(new_image), cv2.COLOR_RGB2BGR)
  112. if self.model.apply_ocr:
  113. ocr_res = self.model.ocr_model.ocr(
  114. new_image, mfd_res=adjusted_mfdetrec_res
  115. )[0]
  116. else:
  117. ocr_res = self.model.ocr_model.ocr(
  118. new_image, mfd_res=adjusted_mfdetrec_res, rec=False
  119. )[0]
  120. # Integration results
  121. if ocr_res:
  122. ocr_result_list = get_ocr_result_list(ocr_res, useful_list)
  123. layout_res.extend(ocr_result_list)
  124. ocr_time += time.time() - ocr_start
  125. ocr_count += len(ocr_res_list)
  126. # 表格识别 table recognition
  127. if self.model.apply_table:
  128. table_start = time.time()
  129. for res in table_res_list:
  130. new_image, _ = crop_img(res, pil_img)
  131. single_table_start_time = time.time()
  132. html_code = None
  133. if self.model.table_model_name == MODEL_NAME.STRUCT_EQTABLE:
  134. with torch.no_grad():
  135. table_result = self.model.table_model.predict(
  136. new_image, 'html'
  137. )
  138. if len(table_result) > 0:
  139. html_code = table_result[0]
  140. elif self.model.table_model_name == MODEL_NAME.TABLE_MASTER:
  141. html_code = self.model.table_model.img2html(new_image)
  142. elif self.model.table_model_name == MODEL_NAME.RAPID_TABLE:
  143. html_code, table_cell_bboxes, elapse = (
  144. self.model.table_model.predict(new_image)
  145. )
  146. run_time = time.time() - single_table_start_time
  147. if run_time > self.model.table_max_time:
  148. logger.warning(
  149. f'table recognition processing exceeds max time {self.model.table_max_time}s'
  150. )
  151. # 判断是否返回正常
  152. if html_code:
  153. expected_ending = html_code.strip().endswith(
  154. '</html>'
  155. ) or html_code.strip().endswith('</table>')
  156. if expected_ending:
  157. res['html'] = html_code
  158. else:
  159. logger.warning(
  160. 'table recognition processing fails, not found expected HTML table end'
  161. )
  162. else:
  163. logger.warning(
  164. 'table recognition processing fails, not get html return'
  165. )
  166. table_time += time.time() - table_start
  167. table_count += len(table_res_list)
  168. if self.model.apply_ocr:
  169. logger.info(f'ocr time: {round(ocr_time, 2)}, image num: {ocr_count}')
  170. else:
  171. logger.info(f'det time: {round(ocr_time, 2)}, image num: {ocr_count}')
  172. if self.model.apply_table:
  173. logger.info(f'table time: {round(table_time, 2)}, image num: {table_count}')
  174. return images_layout_res
  175. def doc_batch_analyze(
  176. dataset: Dataset,
  177. ocr: bool = False,
  178. show_log: bool = False,
  179. start_page_id=0,
  180. end_page_id=None,
  181. lang=None,
  182. layout_model=None,
  183. formula_enable=None,
  184. table_enable=None,
  185. batch_ratio: int | None = None,
  186. ) -> InferenceResult:
  187. """Perform batch analysis on a document dataset.
  188. Args:
  189. dataset (Dataset): The dataset containing document pages to be analyzed.
  190. ocr (bool, optional): Flag to enable OCR (Optical Character Recognition). Defaults to False.
  191. show_log (bool, optional): Flag to enable logging. Defaults to False.
  192. start_page_id (int, optional): The starting page ID for analysis. Defaults to 0.
  193. end_page_id (int, optional): The ending page ID for analysis. Defaults to None, which means analyze till the last page.
  194. lang (str, optional): Language for OCR. Defaults to None.
  195. layout_model (optional): Layout model to be used for analysis. Defaults to None.
  196. formula_enable (optional): Flag to enable formula detection. Defaults to None.
  197. table_enable (optional): Flag to enable table detection. Defaults to None.
  198. batch_ratio (int | None, optional): Ratio for batch processing. Defaults to None, which sets it to 1.
  199. Raises:
  200. CUDA_NOT_AVAILABLE: If CUDA is not available, raises an exception as batch analysis is not supported in CPU mode.
  201. Returns:
  202. InferenceResult: The result of the batch analysis containing the analyzed data and the dataset.
  203. """
  204. if not torch.cuda.is_available():
  205. raise CUDA_NOT_AVAILABLE('batch analyze not support in CPU mode')
  206. lang = None if lang == '' else lang
  207. # TODO: auto detect batch size
  208. batch_ratio = 1 if batch_ratio is None else batch_ratio
  209. end_page_id = end_page_id if end_page_id else len(dataset)
  210. model_manager = ModelSingleton()
  211. custom_model: CustomPEKModel = model_manager.get_model(
  212. ocr, show_log, lang, layout_model, formula_enable, table_enable
  213. )
  214. batch_model = BatchAnalyze(model=custom_model, batch_ratio=batch_ratio)
  215. model_json = []
  216. # batch analyze
  217. images = []
  218. for index in range(len(dataset)):
  219. if start_page_id <= index <= end_page_id:
  220. page_data = dataset.get_page(index)
  221. img_dict = page_data.get_image()
  222. images.append(img_dict['img'])
  223. analyze_result = batch_model(images)
  224. for index in range(len(dataset)):
  225. page_data = dataset.get_page(index)
  226. img_dict = page_data.get_image()
  227. page_width = img_dict['width']
  228. page_height = img_dict['height']
  229. if start_page_id <= index <= end_page_id:
  230. result = analyze_result.pop(0)
  231. else:
  232. result = []
  233. page_info = {'page_no': index, 'height': page_height, 'width': page_width}
  234. page_dict = {'layout_dets': result, 'page_info': page_info}
  235. model_json.append(page_dict)
  236. # TODO: clean memory when gpu memory is not enough
  237. clean_memory_start_time = time.time()
  238. clean_memory()
  239. logger.info(f'clean memory time: {round(time.time() - clean_memory_start_time, 2)}')
  240. return InferenceResult(model_json, dataset)