cli.py 4.02 KB
Newer Older
icecraft's avatar
icecraft committed
1
import os
2
3
import shutil
import tempfile
icecraft's avatar
icecraft committed
4
import click
5
import fitz
icecraft's avatar
icecraft committed
6
from loguru import logger
7
from pathlib import Path
8

icecraft's avatar
icecraft committed
9
import magic_pdf.model as model_config
10
from magic_pdf.data.data_reader_writer import FileBasedDataReader
11
from magic_pdf.libs.version import __version__
12
from magic_pdf.tools.common import do_parse, parse_pdf_methods
13
14
15
16
17
from magic_pdf.utils.office_to_pdf import convert_file_to_pdf

pdf_suffixes = ['.pdf']
ms_office_suffixes = ['.ppt', '.pptx', '.doc', '.docx']
image_suffixes = ['.png', '.jpg']
icecraft's avatar
icecraft committed
18
19
20


@click.command()
21
22
23
24
@click.version_option(__version__,
                      '--version',
                      '-v',
                      help='display the version and exit')
icecraft's avatar
icecraft committed
25
@click.option(
26
27
28
    '-p',
    '--path',
    'path',
icecraft's avatar
icecraft committed
29
30
    type=click.Path(exists=True),
    required=True,
31
    help='local filepath or directory. support PDF, PPT, PPTX, DOC, DOCX, PNG, JPG files',
icecraft's avatar
icecraft committed
32
33
)
@click.option(
34
35
36
37
38
39
    '-o',
    '--output-dir',
    'output_dir',
    type=click.Path(),
    required=True,
    help='output local directory',
icecraft's avatar
icecraft committed
40
41
)
@click.option(
42
43
44
    '-m',
    '--method',
    'method',
icecraft's avatar
icecraft committed
45
    type=parse_pdf_methods,
46
    help="""the method for parsing pdf.
icecraft's avatar
icecraft committed
47
ocr: using ocr technique to extract information from pdf.
48
49
50
txt: suitable for the text-based pdf only and outperform ocr.
auto: automatically choose the best method for parsing pdf from ocr and txt.
without method specified, auto will be used by default.""",
51
    default='auto',
icecraft's avatar
icecraft committed
52
)
53
54
55
56
57
58
59
60
@click.option(
    '-l',
    '--lang',
    'lang',
    type=str,
    help="""
    Input the languages in the pdf (if known) to improve OCR accuracy.  Optional.
    You should input "Abbreviation" with language form url:
61
    https://paddlepaddle.github.io/PaddleOCR/latest/en/ppocr/blog/multi_languages.html#5-support-languages-and-abbreviations
62
63
64
    """,
    default=None,
)
65
@click.option(
66
67
68
    '-d',
    '--debug',
    'debug_able',
69
    type=bool,
70
    help='Enables detailed debugging information during the execution of the CLI commands.',
71
72
    default=False,
)
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
@click.option(
    '-s',
    '--start',
    'start_page_id',
    type=int,
    help='The starting page for PDF parsing, beginning from 0.',
    default=0,
)
@click.option(
    '-e',
    '--end',
    'end_page_id',
    type=int,
    help='The ending page for PDF parsing, beginning from 0.',
    default=None,
)
89
def cli(path, output_dir, method, lang, debug_able, start_page_id, end_page_id):
icecraft's avatar
icecraft committed
90
    model_config.__use_inside_model__ = True
91
92
    model_config.__model_mode__ = 'full'
    os.makedirs(output_dir, exist_ok=True)
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    temp_dir = tempfile.mkdtemp()
    def read_fn(path: Path):
        if path.suffix in ms_office_suffixes:
            convert_file_to_pdf(str(path), temp_dir)
            fn = os.path.join(temp_dir, f"{path.stem}.pdf")
        elif path.suffix in image_suffixes:
            with open(str(path), 'rb') as f:
                bits = f.read(_)
            pdf_bytes = fitz.open(stream=bits).convert_to_pdf()
            fn = os.path.join(temp_dir, f"{path.stem}.pdf")
            with open(fn, 'wb') as f:
                f.write(pdf_bytes)
        elif path.suffix in pdf_suffixes:
            fn = str(path)
        else:
            raise Exception(f"Unknown file suffix: {path.suffix}")
        
        disk_rw = FileBasedDataReader(os.path.dirname(fn))
        return disk_rw.read(os.path.basename(fn))
icecraft's avatar
icecraft committed
112

113
    def parse_doc(doc_path: Path):
icecraft's avatar
icecraft committed
114
115
116
117
118
119
120
121
122
        try:
            file_name = str(Path(doc_path).stem)
            pdf_data = read_fn(doc_path)
            do_parse(
                output_dir,
                file_name,
                pdf_data,
                [],
                method,
123
                debug_able,
124
125
                start_page_id=start_page_id,
                end_page_id=end_page_id,
126
                lang=lang
icecraft's avatar
icecraft committed
127
128
129
130
131
132
            )

        except Exception as e:
            logger.exception(e)

    if os.path.isdir(path):
133
134
135
        for doc_path in Path(path).glob('*'):
            if doc_path.suffix in pdf_suffixes + image_suffixes + ms_office_suffixes:
                parse_doc(doc_path)
icecraft's avatar
icecraft committed
136
137
138
    else:
        parse_doc(path)

139
140
    shutil.rmtree(temp_dir)

icecraft's avatar
icecraft committed
141

142
if __name__ == '__main__':
icecraft's avatar
icecraft committed
143
    cli()