client.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import os
  3. import click
  4. from pathlib import Path
  5. import torch
  6. from loguru import logger
  7. from mineru.utils.config_reader import get_device
  8. from mineru.utils.model_utils import get_vram
  9. from ..version import __version__
  10. from .common import do_parse, read_fn, pdf_suffixes, image_suffixes
  11. @click.command()
  12. @click.version_option(__version__,
  13. '--version',
  14. '-v',
  15. help='display the version and exit')
  16. @click.option(
  17. '-p',
  18. '--path',
  19. 'input_path',
  20. type=click.Path(exists=True),
  21. required=True,
  22. help='local filepath or directory. support pdf, png, jpg, jpeg files',
  23. )
  24. @click.option(
  25. '-o',
  26. '--output',
  27. 'output_dir',
  28. type=click.Path(),
  29. required=True,
  30. help='output local directory',
  31. )
  32. @click.option(
  33. '-m',
  34. '--method',
  35. 'method',
  36. type=click.Choice(['auto', 'txt', 'ocr']),
  37. help="""the method for parsing pdf:
  38. auto: Automatically determine the method based on the file type.
  39. txt: Use text extraction method.
  40. ocr: Use OCR method for image-based PDFs.
  41. Without method specified, 'auto' will be used by default.
  42. Adapted only for the case where the backend is set to "pipeline".""",
  43. default='auto',
  44. )
  45. @click.option(
  46. '-b',
  47. '--backend',
  48. 'backend',
  49. type=click.Choice(['pipeline', 'vlm-transformers', 'vlm-sglang-engine', 'vlm-sglang-client']),
  50. help="""the backend for parsing pdf:
  51. pipeline: More general.
  52. vlm-transformers: More general.
  53. vlm-sglang-engine: Faster(engine).
  54. vlm-sglang-client: Faster(client).
  55. without method specified, pipeline will be used by default.""",
  56. default='pipeline',
  57. )
  58. @click.option(
  59. '-l',
  60. '--lang',
  61. 'lang',
  62. type=click.Choice(['ch', 'ch_server', 'ch_lite', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka']),
  63. help="""
  64. Input the languages in the pdf (if known) to improve OCR accuracy. Optional.
  65. Without languages specified, 'ch' will be used by default.
  66. Adapted only for the case where the backend is set to "pipeline".
  67. """,
  68. default='ch',
  69. )
  70. @click.option(
  71. '-u',
  72. '--url',
  73. 'server_url',
  74. type=str,
  75. help="""
  76. When the backend is `sglang-client`, you need to specify the server_url, for example:`http://127.0.0.1:30000`
  77. """,
  78. default=None,
  79. )
  80. @click.option(
  81. '-s',
  82. '--start',
  83. 'start_page_id',
  84. type=int,
  85. help='The starting page for PDF parsing, beginning from 0.',
  86. default=0,
  87. )
  88. @click.option(
  89. '-e',
  90. '--end',
  91. 'end_page_id',
  92. type=int,
  93. help='The ending page for PDF parsing, beginning from 0.',
  94. default=None,
  95. )
  96. @click.option(
  97. '-f',
  98. '--formula',
  99. 'formula_enable',
  100. type=bool,
  101. help='Enable formula parsing. Default is True. Adapted only for the case where the backend is set to "pipeline".',
  102. default=True,
  103. )
  104. @click.option(
  105. '-t',
  106. '--table',
  107. 'table_enable',
  108. type=bool,
  109. help='Enable table parsing. Default is True. Adapted only for the case where the backend is set to "pipeline".',
  110. default=True,
  111. )
  112. @click.option(
  113. '-d',
  114. '--device',
  115. 'device_mode',
  116. type=str,
  117. help='Device mode for model inference, e.g., "cpu", "cuda", "cuda:0", "npu", "npu:0", "mps". Adapted only for the case where the backend is set to "pipeline". ',
  118. default=None,
  119. )
  120. @click.option(
  121. '--vram',
  122. 'virtual_vram',
  123. type=int,
  124. help='Upper limit of GPU memory occupied by a single process. Adapted only for the case where the backend is set to "pipeline". ',
  125. default=None,
  126. )
  127. @click.option(
  128. '--source',
  129. 'model_source',
  130. type=click.Choice(['huggingface', 'modelscope', 'local']),
  131. help="""
  132. The source of the model repository. Default is 'huggingface'.
  133. """,
  134. default='huggingface',
  135. )
  136. def main(input_path, output_dir, method, backend, lang, server_url, start_page_id, end_page_id, formula_enable, table_enable, device_mode, virtual_vram, model_source):
  137. def get_device_mode() -> str:
  138. if device_mode is not None:
  139. return device_mode
  140. else:
  141. return get_device()
  142. if os.getenv('MINERU_DEVICE_MODE', None) is None:
  143. os.environ['MINERU_DEVICE_MODE'] = get_device_mode()
  144. def get_virtual_vram_size() -> int:
  145. if virtual_vram is not None:
  146. return virtual_vram
  147. if get_device_mode().startswith("cuda") or get_device_mode().startswith("npu"):
  148. return round(get_vram(get_device_mode()))
  149. return 1
  150. if os.getenv('MINERU_VIRTUAL_VRAM_SIZE', None) is None:
  151. os.environ['MINERU_VIRTUAL_VRAM_SIZE']= str(get_virtual_vram_size())
  152. if os.getenv('MINERU_MODEL_SOURCE', None) is None:
  153. os.environ['MINERU_MODEL_SOURCE'] = model_source
  154. os.makedirs(output_dir, exist_ok=True)
  155. def parse_doc(path_list: list[Path]):
  156. try:
  157. file_name_list = []
  158. pdf_bytes_list = []
  159. lang_list = []
  160. for path in path_list:
  161. file_name = str(Path(path).stem)
  162. pdf_bytes = read_fn(path)
  163. file_name_list.append(file_name)
  164. pdf_bytes_list.append(pdf_bytes)
  165. lang_list.append(lang)
  166. do_parse(
  167. output_dir=output_dir,
  168. pdf_file_names=file_name_list,
  169. pdf_bytes_list=pdf_bytes_list,
  170. p_lang_list=lang_list,
  171. backend=backend,
  172. parse_method=method,
  173. p_formula_enable=formula_enable,
  174. p_table_enable=table_enable,
  175. server_url=server_url,
  176. start_page_id=start_page_id,
  177. end_page_id=end_page_id
  178. )
  179. except Exception as e:
  180. logger.exception(e)
  181. if os.path.isdir(input_path):
  182. doc_path_list = []
  183. for doc_path in Path(input_path).glob('*'):
  184. if doc_path.suffix in pdf_suffixes + image_suffixes:
  185. doc_path_list.append(doc_path)
  186. parse_doc(doc_path_list)
  187. else:
  188. parse_doc([Path(input_path)])
  189. if __name__ == '__main__':
  190. main()