vvcc-wad commited on
Commit
3ce490f
·
verified ·
1 Parent(s): fb52fcc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -0
app.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Opendatalab. All rights reserved.
2
+
3
+ import base64
4
+ import json
5
+ import os
6
+ import time
7
+ import zipfile
8
+ from pathlib import Path
9
+ import re
10
+ import uuid
11
+ import pymupdf
12
+
13
+ # os.system('pip install -U magic-pdf==0.10.5')
14
+ os.system('pip uninstall -y magic-pdf')
15
+ os.system('pip install git+https://github.com/opendatalab/MinerU.git@dev')
16
+
17
+ os.system('wget https://github.com/opendatalab/MinerU/raw/dev/scripts/download_models_hf.py -O download_models_hf.py')
18
+ os.system('python download_models_hf.py')
19
+
20
+ with open('/home/user/magic-pdf.json', 'r') as file:
21
+ data = json.load(file)
22
+
23
+ # 修改处1:允许cpu和gpu自动选择,cuda不可用自动回落到cpu
24
+ data['device-mode'] = "cuda" if os.system("command -v nvidia-smi > /dev/null") == 0 else "cpu"
25
+
26
+ if os.getenv('apikey'):
27
+ data['llm-aided-config']['title_aided']['api_key'] = os.getenv('apikey')
28
+ data['llm-aided-config']['title_aided']['enable'] = True
29
+
30
+ with open('/home/user/magic-pdf.json', 'w') as file:
31
+ json.dump(data, file, indent=4)
32
+
33
+ from gradio_pdf import PDF
34
+
35
+ import gradio as gr
36
+ from loguru import logger
37
+
38
+ from magic_pdf.data.data_reader_writer import FileBasedDataReader
39
+ from magic_pdf.libs.hash_utils import compute_sha256
40
+ from magic_pdf.tools.common import do_parse, prepare_env
41
+
42
+
43
+ def read_fn(path):
44
+ disk_rw = FileBasedDataReader(os.path.dirname(path))
45
+ return disk_rw.read(os.path.basename(path))
46
+
47
+
48
+ def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, layout_mode, formula_enable, table_enable, language):
49
+ os.makedirs(output_dir, exist_ok=True)
50
+
51
+ try:
52
+ file_name = f"{str(Path(doc_path).stem)}_{time.time()}"
53
+ pdf_data = read_fn(doc_path)
54
+ parse_method = "ocr" if is_ocr else "auto"
55
+ local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
56
+ do_parse(
57
+ output_dir,
58
+ file_name,
59
+ pdf_data,
60
+ [],
61
+ parse_method,
62
+ False,
63
+ end_page_id=end_page_id,
64
+ layout_model=layout_mode,
65
+ formula_enable=formula_enable,
66
+ table_enable=table_enable,
67
+ lang=language,
68
+ f_dump_orig_pdf=False,
69
+ )
70
+ return local_md_dir, file_name
71
+ except Exception as e:
72
+ logger.exception(e)
73
+
74
+
75
+ def compress_directory_to_zip(directory_path, output_zip_path):
76
+ try:
77
+ with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
78
+ for root, dirs, files in os.walk(directory_path):
79
+ for file in files:
80
+ file_path = os.path.join(root, file)
81
+ arcname = os.path.relpath(file_path, directory_path)
82
+ zipf.write(file_path, arcname)
83
+ return 0
84
+ except Exception as e:
85
+ logger.exception(e)
86
+ return -1
87
+
88
+
89
+ def image_to_base64(image_path):
90
+ with open(image_path, "rb") as image_file:
91
+ return base64.b64encode(image_file.read()).decode('utf-8')
92
+
93
+
94
+ def replace_image_with_base64(markdown_text, image_dir_path):
95
+ pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
96
+
97
+ # 使用lambda简化函数
98
+ return re.sub(pattern,
99
+ lambda match: f"![{match.group(1)}](data:image/jpeg;base64,{image_to_base64(os.path.join(image_dir_path, match.group(1)))})",
100
+ markdown_text)
101
+
102
+
103
+ def to_markdown(file_path, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language):
104
+ file_path = to_pdf(file_path)
105
+ # 修改处2:不再限制最大20页
106
+ local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1, is_ocr,
107
+ layout_mode, formula_enable, table_enable, language)
108
+ archive_zip_path = os.path.join("./output", compute_sha256(local_md_dir) + ".zip")
109
+ zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
110
+ if zip_archive_success == 0:
111
+ logger.info("压缩成功")
112
+ else:
113
+ logger.error("压缩失败")
114
+ md_path = os.path.join(local_md_dir, file_name + ".md")
115
+ with open(md_path, 'r', encoding='utf-8') as f:
116
+ txt_content = f.read()
117
+ md_content = replace_image_with_base64(txt_content, local_md_dir)
118
+ new_pdf_path = os.path.join(local_md_dir, file_name + "_layout.pdf")
119
+
120
+ return md_content, txt_content, archive_zip_path, new_pdf_path
121
+
122
+
123
+ latex_delimiters = [{"left": "$$", "right": "$$", "display": True},
124
+ {"left": '$', "right": '$', "display": False}]
125
+
126
+
127
+ def init_model():
128
+ from magic_pdf.model.doc_analyze_by_custom_model import ModelSingleton
129
+ try:
130
+ model_manager = ModelSingleton()
131
+ model_manager.get_model(False, False)
132
+ model_manager.get_model(True, False)
133
+ return 0
134
+ except Exception as e:
135
+ logger.exception(e)
136
+ return -1
137
+
138
+
139
+ model_init = init_model()
140
+ logger.info(f"model_init: {model_init}")
141
+
142
+ with open("header.html", "r") as file:
143
+ header = file.read()
144
+
145
+ latin_lang = ['af', 'az', 'bs', 'cs', 'cy', 'da', 'de', 'es', 'et', 'fr', 'ga', 'hr',
146
+ 'hu', 'id', 'is', 'it', 'ku', 'la', 'lt', 'lv', 'mi', 'ms', 'mt', 'nl',
147
+ 'no', 'oc', 'pi', 'pl', 'pt', 'ro', 'rs_latin', 'sk', 'sl', 'sq', 'sv',
148
+ 'sw', 'tl', 'tr', 'uz', 'vi', 'french', 'german']
149
+ arabic_lang = ['ar', 'fa', 'ug', 'ur']
150
+ cyrillic_lang = ['ru', 'rs_cyrillic', 'be', 'bg', 'uk', 'mn', 'abq', 'ady', 'kbd', 'ava',
151
+ 'dar', 'inh', 'che', 'lbe', 'lez', 'tab']
152
+ devanagari_lang = ['hi', 'mr', 'ne', 'bh', 'mai', 'ang', 'bho', 'mah', 'sck', 'new', 'gom',
153
+ 'sa', 'bgc']
154
+ other_lang = ['ch', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka']
155
+ all_lang = ['', 'auto'] + other_lang + latin_lang + arabic_lang + cyrillic_lang + devanagari_lang
156
+
157
+
158
+ def to_pdf(file_path):
159
+ with pymupdf.open(file_path) as f:
160
+ if f.is_pdf:
161
+ return file_path
162
+ pdf_bytes = f.convert_to_pdf()
163
+ tmp_file_path = os.path.join(os.path.dirname(file_path), f"{uuid.uuid4()}.pdf")
164
+ with open(tmp_file_path, 'wb') as tmp_pdf_file:
165
+ tmp_pdf_file.write(pdf_bytes)
166
+ return tmp_file_path
167
+
168
+ if __name__ == "__main__":
169
+ with gr.Blocks() as demo:
170
+ gr.HTML(header)
171
+ with gr.Row():
172
+ with gr.Column(scale=5):
173
+ file = gr.File(label="Please upload a PDF or image", file_types=[".pdf", ".png", ".jpeg", ".jpg"])
174
+ # 修改处3:gradio界面页数最大改为99999
175
+ max_pages = gr.Slider(1, 99999, 10, step=1, label='Max convert pages')
176
+ with gr.Row():
177
+ layout_mode = gr.Dropdown(["doclayout_yolo"], label="Layout model", value="doclayout_yolo")
178
+ language = gr.Dropdown(all_lang, label="Language", value='auto')
179
+ with gr.Row():
180
+ formula_enable = gr.Checkbox(label="Enable formula recognition", value=True)
181
+ is_ocr = gr.Checkbox(label="Force enable OCR", value=False)
182
+ table_enable = gr.Checkbox(label="Enable table recognition(test)", value=True)
183
+ with gr.Row():
184
+ change_bu = gr.Button("Convert")
185
+ clear_bu = gr.ClearButton(value="Clear")
186
+ pdf_show = PDF(label='PDF preview', interactive=False, visible=True, height=800)
187
+
188
+ with gr.Column(scale=5):
189
+ output_file = gr.File(label="convert result", interactive=False)
190
+ md = gr.Markdown()
191
+ md_text = gr.TextArea(lines=45)
192
+
193
+ file.change(fn=to_pdf, inputs=file, outputs=pdf_show)
194
+ change_bu.click(fn=to_markdown, inputs=[file, max_pages, is_ocr, layout_mode, formula_enable, table_enable, language],
195
+ outputs=[md, md_text, output_file, pdf_show])
196
+ clear_bu.add([file, md, pdf_show, md_text, output_file, is_ocr])
197
+
198
+ demo.launch(ssr_mode=True)