app.py 8.95 KB
Newer Older
1
2
3
4
# Copyright (c) Opendatalab. All rights reserved.

import base64
import os
5
import re
6
import time
7
import uuid
8
9
10
import zipfile
from pathlib import Path

11
import gradio as gr
12
import pymupdf
13
from gradio_pdf import PDF
14
15
from loguru import logger

16
from magic_pdf.data.data_reader_writer import FileBasedDataReader
17
from magic_pdf.libs.config_reader import get_device
18
from magic_pdf.libs.hash_utils import compute_sha256
19
from magic_pdf.model.sub_modules.model_utils import get_vram
20
21
22
23
from magic_pdf.tools.common import do_parse, prepare_env


def read_fn(path):
24
    disk_rw = FileBasedDataReader(os.path.dirname(path))
25
    return disk_rw.read(os.path.basename(path))
26
27


28
def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, layout_mode, formula_enable, table_enable, language):
29
30
31
    os.makedirs(output_dir, exist_ok=True)

    try:
32
        file_name = f'{str(Path(doc_path).stem)}_{time.time()}'
33
34
        pdf_data = read_fn(doc_path)
        if is_ocr:
35
            parse_method = 'ocr'
36
        else:
37
            parse_method = 'auto'
38
39
40
41
42
43
44
45
46
        local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
        do_parse(
            output_dir,
            file_name,
            pdf_data,
            [],
            parse_method,
            False,
            end_page_id=end_page_id,
47
48
49
50
            layout_model=layout_mode,
            formula_enable=formula_enable,
            table_enable=table_enable,
            lang=language,
51
52
53
54
55
56
57
        )
        return local_md_dir, file_name
    except Exception as e:
        logger.exception(e)


def compress_directory_to_zip(directory_path, output_zip_path):
58
    """压缩指定目录到一个 ZIP 文件。
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

    :param directory_path: 要压缩的目录路径
    :param output_zip_path: 输出的 ZIP 文件路径
    """
    try:
        with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:

            # 遍历目录中的所有文件和子目录
            for root, dirs, files in os.walk(directory_path):
                for file in files:
                    # 构建完整的文件路径
                    file_path = os.path.join(root, file)
                    # 计算相对路径
                    arcname = os.path.relpath(file_path, directory_path)
                    # 添加文件到 ZIP 文件
                    zipf.write(file_path, arcname)
        return 0
    except Exception as e:
        logger.exception(e)
        return -1


def image_to_base64(image_path):
82
    with open(image_path, 'rb') as image_file:
83
84
85
86
87
88
89
90
91
92
93
94
        return base64.b64encode(image_file.read()).decode('utf-8')


def replace_image_with_base64(markdown_text, image_dir_path):
    # 匹配Markdown中的图片标签
    pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'

    # 替换图片链接
    def replace(match):
        relative_path = match.group(1)
        full_path = os.path.join(image_dir_path, relative_path)
        base64_image = image_to_base64(full_path)
95
        return f'![{relative_path}](data:image/jpeg;base64,{base64_image})'
96
97
98
99
100

    # 应用替换
    return re.sub(pattern, replace, markdown_text)


101
def to_markdown(file_path, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language):
102
    # 获取识别的md文件以及压缩包文件路径
103
104
    local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1, is_ocr,
                                        layout_mode, formula_enable, table_enable, language)
105
    archive_zip_path = os.path.join('./output', compute_sha256(local_md_dir) + '.zip')
106
107
    zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
    if zip_archive_success == 0:
108
        logger.info('压缩成功')
109
    else:
110
111
        logger.error('压缩失败')
    md_path = os.path.join(local_md_dir, file_name + '.md')
112
113
114
115
    with open(md_path, 'r', encoding='utf-8') as f:
        txt_content = f.read()
    md_content = replace_image_with_base64(txt_content, local_md_dir)
    # 返回转换后的PDF路径
116
    new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')
117
118
119
120

    return md_content, txt_content, archive_zip_path, new_pdf_path


121
122
latex_delimiters = [{'left': '$$', 'right': '$$', 'display': True},
                    {'left': '$', 'right': '$', 'display': False}]
123
124
125
126
127
128


def init_model():
    from magic_pdf.model.doc_analyze_by_custom_model import ModelSingleton
    try:
        model_manager = ModelSingleton()
129
130
131
132
        txt_model = model_manager.get_model(False, False)  # noqa: F841
        logger.info('txt_model init final')
        ocr_model = model_manager.get_model(True, False)  # noqa: F841
        logger.info('ocr_model init final')
133
134
135
136
137
138
139
        return 0
    except Exception as e:
        logger.exception(e)
        return -1


model_init = init_model()
140
logger.info(f'model_init: {model_init}')
141
142


143
with open('header.html', 'r') as file:
144
145
146
    header = file.read()


147
latin_lang = [
148
        'af', 'az', 'bs', 'cs', 'cy', 'da', 'de', 'es', 'et', 'fr', 'ga', 'hr',  # noqa: E126
149
150
151
152
153
154
        'hu', 'id', 'is', 'it', 'ku', 'la', 'lt', 'lv', 'mi', 'ms', 'mt', 'nl',
        'no', 'oc', 'pi', 'pl', 'pt', 'ro', 'rs_latin', 'sk', 'sl', 'sq', 'sv',
        'sw', 'tl', 'tr', 'uz', 'vi', 'french', 'german'
]
arabic_lang = ['ar', 'fa', 'ug', 'ur']
cyrillic_lang = [
155
        'ru', 'rs_cyrillic', 'be', 'bg', 'uk', 'mn', 'abq', 'ady', 'kbd', 'ava',  # noqa: E126
156
157
158
        'dar', 'inh', 'che', 'lbe', 'lez', 'tab'
]
devanagari_lang = [
159
        'hi', 'mr', 'ne', 'bh', 'mai', 'ang', 'bho', 'mah', 'sck', 'new', 'gom',  # noqa: E126
160
161
162
163
        'sa', 'bgc'
]
other_lang = ['ch', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka']

164
all_lang = ['']
165
166
167
all_lang.extend([*other_lang, *latin_lang, *arabic_lang, *cyrillic_lang, *devanagari_lang])


168
169
170
171
172
173
174
175
def to_pdf(file_path):
    with pymupdf.open(file_path) as f:
        if f.is_pdf:
            return file_path
        else:
            pdf_bytes = f.convert_to_pdf()
            # 将pdfbytes 写入到uuid.pdf中
            # 生成唯一的文件名
176
            unique_filename = f'{uuid.uuid4()}.pdf'
177
178
179
180
181
182
183
184
185
186
187

            # 构建完整的文件路径
            tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)

            # 将字节数据写入文件
            with open(tmp_file_path, 'wb') as tmp_pdf_file:
                tmp_pdf_file.write(pdf_bytes)

            return tmp_file_path


188
189
def get_concurrency_limit(vram_threshold=7.5):
    vram = get_vram(device = get_device())
190
191
192
    if vram is not None and isinstance(vram, (int, float)):
        concurrency_limit = max(1, int(vram // vram_threshold))
    else:
193
194
195
196
197
        concurrency_limit = 1
    # logger.info(f'concurrency_limit: {concurrency_limit}')
    return concurrency_limit


198
if __name__ == '__main__':
199
200
201
202
    with gr.Blocks() as demo:
        gr.HTML(header)
        with gr.Row():
            with gr.Column(variant='panel', scale=5):
203
204
                file = gr.File(label='Please upload a PDF or image', file_types=['.pdf', '.png', '.jpeg', '.jpg'])
                max_pages = gr.Slider(1, 10, 5, step=1, label='Max convert pages')
205
                with gr.Row():
206
207
                    layout_mode = gr.Dropdown(['layoutlmv3', 'doclayout_yolo'], label='Layout model', value='layoutlmv3')
                    language = gr.Dropdown(all_lang, label='Language', value='')
208
                with gr.Row():
209
210
211
                    formula_enable = gr.Checkbox(label='Enable formula recognition', value=True)
                    is_ocr = gr.Checkbox(label='Force enable OCR', value=False)
                    table_enable = gr.Checkbox(label='Enable table recognition(test)', value=False)
212
                with gr.Row():
213
214
215
216
217
                    change_bu = gr.Button('Convert')
                    clear_bu = gr.ClearButton(value='Clear')
                pdf_show = PDF(label='PDF preview', interactive=True, height=800)
                with gr.Accordion('Examples:'):
                    example_root = os.path.join(os.path.dirname(__file__), 'examples')
218
219
                    gr.Examples(
                        examples=[os.path.join(example_root, _) for _ in os.listdir(example_root) if
220
                                  _.endswith('pdf')],
221
                        inputs=pdf_show
222
                    )
223
224

            with gr.Column(variant='panel', scale=5):
225
                output_file = gr.File(label='convert result', interactive=False)
226
                with gr.Tabs():
227
228
                    with gr.Tab('Markdown rendering'):
                        md = gr.Markdown(label='Markdown rendering', height=900, show_copy_button=True,
229
                                         latex_delimiters=latex_delimiters, line_breaks=True)
230
                    with gr.Tab('Markdown text'):
231
                        md_text = gr.TextArea(lines=45, show_copy_button=True)
232
        file.upload(fn=to_pdf, inputs=file, outputs=pdf_show)
233
        change_bu.click(fn=to_markdown, inputs=[pdf_show, max_pages, is_ocr, layout_mode, formula_enable, table_enable, language],
234
                        outputs=[md, md_text, output_file, pdf_show], concurrency_limit=get_concurrency_limit())
235
        clear_bu.add([file, md, pdf_show, md_text, output_file, is_ocr, table_enable, language])
236

237
    demo.launch(server_name='0.0.0.0')