cli.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import os
  2. import shutil
  3. import tempfile
  4. import click
  5. import fitz
  6. from loguru import logger
  7. from pathlib import Path
  8. import magic_pdf.model as model_config
  9. from magic_pdf.data.data_reader_writer import FileBasedDataReader
  10. from magic_pdf.libs.version import __version__
  11. from magic_pdf.tools.common import do_parse, parse_pdf_methods
  12. from magic_pdf.utils.office_to_pdf import convert_file_to_pdf
  13. pdf_suffixes = ['.pdf']
  14. ms_office_suffixes = ['.ppt', '.pptx', '.doc', '.docx']
  15. image_suffixes = ['.png', '.jpg']
  16. @click.command()
  17. @click.version_option(__version__,
  18. '--version',
  19. '-v',
  20. help='display the version and exit')
  21. @click.option(
  22. '-p',
  23. '--path',
  24. 'path',
  25. type=click.Path(exists=True),
  26. required=True,
  27. help='local filepath or directory. support PDF, PPT, PPTX, DOC, DOCX, PNG, JPG files',
  28. )
  29. @click.option(
  30. '-o',
  31. '--output-dir',
  32. 'output_dir',
  33. type=click.Path(),
  34. required=True,
  35. help='output local directory',
  36. )
  37. @click.option(
  38. '-m',
  39. '--method',
  40. 'method',
  41. type=parse_pdf_methods,
  42. help="""the method for parsing pdf.
  43. ocr: using ocr technique to extract information from pdf.
  44. txt: suitable for the text-based pdf only and outperform ocr.
  45. auto: automatically choose the best method for parsing pdf from ocr and txt.
  46. without method specified, auto will be used by default.""",
  47. default='auto',
  48. )
  49. @click.option(
  50. '-l',
  51. '--lang',
  52. 'lang',
  53. type=str,
  54. help="""
  55. Input the languages in the pdf (if known) to improve OCR accuracy. Optional.
  56. You should input "Abbreviation" with language form url:
  57. https://paddlepaddle.github.io/PaddleOCR/latest/en/ppocr/blog/multi_languages.html#5-support-languages-and-abbreviations
  58. """,
  59. default=None,
  60. )
  61. @click.option(
  62. '-d',
  63. '--debug',
  64. 'debug_able',
  65. type=bool,
  66. help='Enables detailed debugging information during the execution of the CLI commands.',
  67. default=False,
  68. )
  69. @click.option(
  70. '-s',
  71. '--start',
  72. 'start_page_id',
  73. type=int,
  74. help='The starting page for PDF parsing, beginning from 0.',
  75. default=0,
  76. )
  77. @click.option(
  78. '-e',
  79. '--end',
  80. 'end_page_id',
  81. type=int,
  82. help='The ending page for PDF parsing, beginning from 0.',
  83. default=None,
  84. )
  85. def cli(path, output_dir, method, lang, debug_able, start_page_id, end_page_id):
  86. model_config.__use_inside_model__ = True
  87. model_config.__model_mode__ = 'full'
  88. os.makedirs(output_dir, exist_ok=True)
  89. temp_dir = tempfile.mkdtemp()
  90. def read_fn(path: Path):
  91. if path.suffix in ms_office_suffixes:
  92. convert_file_to_pdf(str(path), temp_dir)
  93. fn = os.path.join(temp_dir, f"{path.stem}.pdf")
  94. elif path.suffix in image_suffixes:
  95. with open(str(path), 'rb') as f:
  96. bits = f.read()
  97. pdf_bytes = fitz.open(stream=bits).convert_to_pdf()
  98. fn = os.path.join(temp_dir, f"{path.stem}.pdf")
  99. with open(fn, 'wb') as f:
  100. f.write(pdf_bytes)
  101. elif path.suffix in pdf_suffixes:
  102. fn = str(path)
  103. else:
  104. raise Exception(f"Unknown file suffix: {path.suffix}")
  105. disk_rw = FileBasedDataReader(os.path.dirname(fn))
  106. return disk_rw.read(os.path.basename(fn))
  107. def parse_doc(doc_path: Path):
  108. try:
  109. file_name = str(Path(doc_path).stem)
  110. pdf_data = read_fn(doc_path)
  111. do_parse(
  112. output_dir,
  113. file_name,
  114. pdf_data,
  115. [],
  116. method,
  117. debug_able,
  118. start_page_id=start_page_id,
  119. end_page_id=end_page_id,
  120. lang=lang
  121. )
  122. except Exception as e:
  123. logger.exception(e)
  124. if os.path.isdir(path):
  125. for doc_path in Path(path).glob('*'):
  126. if doc_path.suffix in pdf_suffixes + image_suffixes + ms_office_suffixes:
  127. parse_doc(doc_path)
  128. else:
  129. parse_doc(Path(path))
  130. shutil.rmtree(temp_dir)
  131. if __name__ == '__main__':
  132. cli()