app.py 8.02 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
12
import gradio as gr
from gradio_pdf import PDF
13
14
from loguru import logger

15
from mineru.cli.common import prepare_env, do_parse, read_fn
16
from mineru.utils.hash_utils import str_sha256
17
18


19
def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, formula_enable, table_enable, language):
20
21
22
    os.makedirs(output_dir, exist_ok=True)

    try:
23
        file_name = f'{str(Path(doc_path).stem)}_{time.strftime("%y%m%d_%H%M%S")}'
24
25
        pdf_data = read_fn(doc_path)
        if is_ocr:
26
            parse_method = 'ocr'
27
        else:
28
            parse_method = 'auto'
29
30
        local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
        do_parse(
31
32
33
34
35
            output_dir=output_dir,
            pdf_file_names=[file_name],
            pdf_bytes_list=[pdf_data],
            p_lang_list=[language],
            parse_method=parse_method,
36
            end_page_id=end_page_id,
37
38
            p_formula_enable=formula_enable,
            p_table_enable=table_enable,
39
40
41
42
43
44
45
        )
        return local_md_dir, file_name
    except Exception as e:
        logger.exception(e)


def compress_directory_to_zip(directory_path, output_zip_path):
46
    """压缩指定目录到一个 ZIP 文件。
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

    :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):
70
    with open(image_path, 'rb') as image_file:
71
72
73
74
75
76
77
78
79
80
81
82
        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)
83
        return f'![{relative_path}](data:image/jpeg;base64,{base64_image})'
84
85
86
87
88

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


89
def to_markdown(file_path, end_pages, is_ocr, formula_enable, table_enable, language):
90
    file_path = to_pdf(file_path)
91
    # 获取识别的md文件以及压缩包文件路径
92
93
    local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1, is_ocr, formula_enable, table_enable, language)
    archive_zip_path = os.path.join('./output', str_sha256(local_md_dir) + '.zip')
94
95
    zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
    if zip_archive_success == 0:
96
        logger.info('压缩成功')
97
    else:
98
99
        logger.error('压缩失败')
    md_path = os.path.join(local_md_dir, file_name + '.md')
100
101
102
103
    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路径
104
    new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')
105
106
107
108

    return md_content, txt_content, archive_zip_path, new_pdf_path


109
110
111
112
113
114
latex_delimiters = [
    {'left': '$$', 'right': '$$', 'display': True},
    {'left': '$', 'right': '$', 'display': False},
    {'left': '\\(', 'right': '\\)', 'display': False},
    {'left': '\\[', 'right': '\\]', 'display': True},
]
115
116


117
with open('header.html', 'r') as file:
118
119
120
    header = file.read()


121
latin_lang = [
122
        'af', 'az', 'bs', 'cs', 'cy', 'da', 'de', 'es', 'et', 'fr', 'ga', 'hr',  # noqa: E126
123
124
125
126
127
128
        '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 = [
129
        'ru', 'rs_cyrillic', 'be', 'bg', 'uk', 'mn', 'abq', 'ady', 'kbd', 'ava',  # noqa: E126
130
131
132
        'dar', 'inh', 'che', 'lbe', 'lez', 'tab'
]
devanagari_lang = [
133
        'hi', 'mr', 'ne', 'bh', 'mai', 'ang', 'bho', 'mah', 'sck', 'new', 'gom',  # noqa: E126
134
135
        'sa', 'bgc'
]
136
other_lang = ['ch', 'ch_lite', 'ch_server', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka']
137
add_lang = ['latin', 'arabic', 'cyrillic', 'devanagari']
138

139
140
141
142
# all_lang = ['', 'auto']
all_lang = []
# all_lang.extend([*other_lang, *latin_lang, *arabic_lang, *cyrillic_lang, *devanagari_lang])
all_lang.extend([*other_lang, *add_lang])
143
144


145
146
147
148
149
150
def safe_stem(file_path):
    stem = Path(file_path).stem
    # 只保留字母、数字、下划线和点,其他字符替换为下划线
    return re.sub(r'[^\w.]', '_', stem)


151
def to_pdf(file_path):
152

153
154
    if file_path is None:
        return None
155

156
    pdf_bytes = read_fn(file_path)
157
158
159

    # unique_filename = f'{uuid.uuid4()}.pdf'
    unique_filename = f'{safe_stem(file_path)}.pdf'
160

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

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

168
    return tmp_file_path
169

170

171
if __name__ == '__main__':
172
173
174
175
    with gr.Blocks() as demo:
        gr.HTML(header)
        with gr.Row():
            with gr.Column(variant='panel', scale=5):
176
                with gr.Row():
177
178
                    file = gr.File(label='Please upload a PDF or image', file_types=['.pdf', '.png', '.jpeg', '.jpg'])
                with gr.Row(equal_height=True):
179
                    with gr.Column(scale=4):
180
181
                        max_pages = gr.Slider(1, 20, 10, step=1, label='Max convert pages')
                    with gr.Column(scale=1):
182
                        language = gr.Dropdown(all_lang, label='Language', value='ch')
183
                with gr.Row():
184
                    is_ocr = gr.Checkbox(label='Force enable OCR', value=False)
185
                    formula_enable = gr.Checkbox(label='Enable formula recognition', value=True)
186
                    table_enable = gr.Checkbox(label='Enable table recognition(test)', value=True)
187
                with gr.Row():
188
189
                    change_bu = gr.Button('Convert')
                    clear_bu = gr.ClearButton(value='Clear')
190
                pdf_show = PDF(label='PDF preview', interactive=False, visible=True, height=800)
191
192
                with gr.Accordion('Examples:'):
                    example_root = os.path.join(os.path.dirname(__file__), 'examples')
193
194
                    gr.Examples(
                        examples=[os.path.join(example_root, _) for _ in os.listdir(example_root) if
195
                                  _.endswith('pdf')],
196
                        inputs=file
197
                    )
198
199

            with gr.Column(variant='panel', scale=5):
200
                output_file = gr.File(label='convert result', interactive=False)
201
                with gr.Tabs():
202
                    with gr.Tab('Markdown rendering'):
203
                        md = gr.Markdown(label='Markdown rendering', height=1100, show_copy_button=True,
204
205
                                         latex_delimiters=latex_delimiters,
                                         line_breaks=True)
206
                    with gr.Tab('Markdown text'):
207
                        md_text = gr.TextArea(lines=45, show_copy_button=True)
208
        file.change(fn=to_pdf, inputs=file, outputs=pdf_show)
209
        change_bu.click(fn=to_markdown, inputs=[file, max_pages, is_ocr, formula_enable, table_enable, language],
210
                        outputs=[md, md_text, output_file, pdf_show])
211
        clear_bu.add([file, md, pdf_show, md_text, output_file, is_ocr])
212

213
    demo.launch(server_name='0.0.0.0')