doc_analyze_by_custom_model.py 7.4 KB

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