client.py 6.4 KB

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