doc_analyze_by_custom_model.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import os
  2. import time
  3. import fitz
  4. import numpy as np
  5. from loguru import logger
  6. # 关闭paddle的信号处理
  7. import paddle
  8. paddle.disable_signal_handler()
  9. os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1' # 禁止albumentations检查更新
  10. os.environ['YOLO_VERBOSE'] = 'False' # disable yolo logger
  11. try:
  12. import torchtext
  13. if torchtext.__version__ >= '0.18.0':
  14. torchtext.disable_torchtext_deprecation_warning()
  15. except ImportError:
  16. pass
  17. import magic_pdf.model as model_config
  18. from magic_pdf.data.dataset import Dataset
  19. from magic_pdf.libs.clean_memory import clean_memory
  20. from magic_pdf.libs.config_reader import (get_device, get_formula_config,
  21. get_layout_config,
  22. get_local_models_dir,
  23. get_table_recog_config)
  24. from magic_pdf.model.model_list import MODEL
  25. from magic_pdf.model.operators import InferenceResult
  26. def dict_compare(d1, d2):
  27. return d1.items() == d2.items()
  28. def remove_duplicates_dicts(lst):
  29. unique_dicts = []
  30. for dict_item in lst:
  31. if not any(
  32. dict_compare(dict_item, existing_dict) for existing_dict in unique_dicts
  33. ):
  34. unique_dicts.append(dict_item)
  35. return unique_dicts
  36. def load_images_from_pdf(
  37. pdf_bytes: bytes, dpi=200, start_page_id=0, end_page_id=None
  38. ) -> list:
  39. try:
  40. from PIL import Image
  41. except ImportError:
  42. logger.error('Pillow not installed, please install by pip.')
  43. exit(1)
  44. images = []
  45. with fitz.open('pdf', pdf_bytes) as doc:
  46. pdf_page_num = doc.page_count
  47. end_page_id = (
  48. end_page_id
  49. if end_page_id is not None and end_page_id >= 0
  50. else pdf_page_num - 1
  51. )
  52. if end_page_id > pdf_page_num - 1:
  53. logger.warning('end_page_id is out of range, use images length')
  54. end_page_id = pdf_page_num - 1
  55. for index in range(0, doc.page_count):
  56. if start_page_id <= index <= end_page_id:
  57. page = doc[index]
  58. mat = fitz.Matrix(dpi / 72, dpi / 72)
  59. pm = page.get_pixmap(matrix=mat, alpha=False)
  60. # If the width or height exceeds 4500 after scaling, do not scale further.
  61. if pm.width > 4500 or pm.height > 4500:
  62. pm = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
  63. img = Image.frombytes('RGB', (pm.width, pm.height), pm.samples)
  64. img = np.array(img)
  65. img_dict = {'img': img, 'width': pm.width, 'height': pm.height}
  66. else:
  67. img_dict = {'img': [], 'width': 0, 'height': 0}
  68. images.append(img_dict)
  69. return images
  70. class ModelSingleton:
  71. _instance = None
  72. _models = {}
  73. def __new__(cls, *args, **kwargs):
  74. if cls._instance is None:
  75. cls._instance = super().__new__(cls)
  76. return cls._instance
  77. def get_model(
  78. self,
  79. ocr: bool,
  80. show_log: bool,
  81. lang=None,
  82. layout_model=None,
  83. formula_enable=None,
  84. table_enable=None,
  85. ):
  86. key = (ocr, show_log, lang, layout_model, formula_enable, table_enable)
  87. if key not in self._models:
  88. self._models[key] = custom_model_init(
  89. ocr=ocr,
  90. show_log=show_log,
  91. lang=lang,
  92. layout_model=layout_model,
  93. formula_enable=formula_enable,
  94. table_enable=table_enable,
  95. )
  96. return self._models[key]
  97. def custom_model_init(
  98. ocr: bool = False,
  99. show_log: bool = False,
  100. lang=None,
  101. layout_model=None,
  102. formula_enable=None,
  103. table_enable=None,
  104. ):
  105. model = None
  106. if model_config.__model_mode__ == 'lite':
  107. logger.warning(
  108. 'The Lite mode is provided for developers to conduct testing only, and the output quality is '
  109. 'not guaranteed to be reliable.'
  110. )
  111. model = MODEL.Paddle
  112. elif model_config.__model_mode__ == 'full':
  113. model = MODEL.PEK
  114. if model_config.__use_inside_model__:
  115. model_init_start = time.time()
  116. if model == MODEL.Paddle:
  117. from magic_pdf.model.pp_structure_v2 import CustomPaddleModel
  118. custom_model = CustomPaddleModel(ocr=ocr, show_log=show_log, lang=lang)
  119. elif model == MODEL.PEK:
  120. from magic_pdf.model.pdf_extract_kit import CustomPEKModel
  121. # 从配置文件读取model-dir和device
  122. local_models_dir = get_local_models_dir()
  123. device = get_device()
  124. layout_config = get_layout_config()
  125. if layout_model is not None:
  126. layout_config['model'] = layout_model
  127. formula_config = get_formula_config()
  128. if formula_enable is not None:
  129. formula_config['enable'] = formula_enable
  130. table_config = get_table_recog_config()
  131. if table_enable is not None:
  132. table_config['enable'] = table_enable
  133. model_input = {
  134. 'ocr': ocr,
  135. 'show_log': show_log,
  136. 'models_dir': local_models_dir,
  137. 'device': device,
  138. 'table_config': table_config,
  139. 'layout_config': layout_config,
  140. 'formula_config': formula_config,
  141. 'lang': lang,
  142. }
  143. custom_model = CustomPEKModel(**model_input)
  144. else:
  145. logger.error('Not allow model_name!')
  146. exit(1)
  147. model_init_cost = time.time() - model_init_start
  148. logger.info(f'model init cost: {model_init_cost}')
  149. else:
  150. logger.error('use_inside_model is False, not allow to use inside model')
  151. exit(1)
  152. return custom_model
  153. def doc_analyze(
  154. dataset: Dataset,
  155. ocr: bool = False,
  156. show_log: bool = False,
  157. start_page_id=0,
  158. end_page_id=None,
  159. lang=None,
  160. layout_model=None,
  161. formula_enable=None,
  162. table_enable=None,
  163. ) -> InferenceResult:
  164. if lang == '':
  165. lang = None
  166. model_manager = ModelSingleton()
  167. custom_model = model_manager.get_model(
  168. ocr, show_log, lang, layout_model, formula_enable, table_enable
  169. )
  170. model_json = []
  171. doc_analyze_start = time.time()
  172. if end_page_id is None:
  173. end_page_id = len(dataset)
  174. for index in range(len(dataset)):
  175. page_data = dataset.get_page(index)
  176. img_dict = page_data.get_image()
  177. img = img_dict['img']
  178. page_width = img_dict['width']
  179. page_height = img_dict['height']
  180. if start_page_id <= index <= end_page_id:
  181. page_start = time.time()
  182. result = custom_model(img)
  183. logger.info(f'-----page_id : {index}, page total time: {round(time.time() - page_start, 2)}-----')
  184. else:
  185. result = []
  186. page_info = {'page_no': index, 'height': page_height, 'width': page_width}
  187. page_dict = {'layout_dets': result, 'page_info': page_info}
  188. model_json.append(page_dict)
  189. gc_start = time.time()
  190. clean_memory()
  191. gc_time = round(time.time() - gc_start, 2)
  192. logger.info(f'gc time: {gc_time}')
  193. doc_analyze_time = round(time.time() - doc_analyze_start, 2)
  194. doc_analyze_speed = round((end_page_id + 1 - start_page_id) / doc_analyze_time, 2)
  195. logger.info(
  196. f'doc analyze time: {round(time.time() - doc_analyze_start, 2)},'
  197. f' speed: {doc_analyze_speed} pages/second'
  198. )
  199. return InferenceResult(model_json, dataset)