myhloli commited on
Commit
7d52d8f
·
1 Parent(s): f13ec23

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -290
app.py CHANGED
@@ -1,298 +1,30 @@
1
- # Copyright (c) Opendatalab. All rights reserved.
2
-
3
- import base64
4
  import os
5
  import json
6
- import re
7
- import time
8
- import zipfile
9
  from loguru import logger
10
- from pathlib import Path
11
-
12
- os.system('pip uninstall -y mineru')
13
- os.system('pip install git+https://github.com/myhloli/Magic-PDF.git@dev')
14
- # os.system('pip install sglang[all]==0.4.8')
15
-
16
- os.system('mineru-models-download -s huggingface -m all')
17
-
18
- try:
19
- with open('/home/user/mineru.json', 'r+') as file:
20
- config = json.load(file)
21
-
22
- delimiters = {
23
- 'display': {'left': '\\[', 'right': '\\]'},
24
- 'inline': {'left': '\\(', 'right': '\\)'}
25
- }
26
-
27
- config['latex-delimiter-config'] = delimiters
28
-
29
- if os.getenv('apikey'):
30
- config['llm-aided-config']['title_aided']['api_key'] = os.getenv('apikey')
31
- config['llm-aided-config']['title_aided']['enable'] = True
32
-
33
- file.seek(0) # 将文件指针移回文件开始位置
34
- file.truncate() # 截断文件,清除原有内容
35
- json.dump(config, file, indent=4) # 写入新内容
36
- except Exception as e:
37
- logger.exception(e)
38
-
39
- from gradio_pdf import PDF
40
- import gradio as gr
41
-
42
- from mineru.cli.common import prepare_env, read_fn, aio_do_parse, pdf_suffixes, image_suffixes
43
- from mineru.utils.hash_utils import str_sha256
44
-
45
- os.environ['MINERU_MODEL_SOURCE'] = 'local'
46
-
47
-
48
- async def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, formula_enable, table_enable, language, backend, url):
49
- os.makedirs(output_dir, exist_ok=True)
50
-
51
- try:
52
- file_name = f'{safe_stem(Path(doc_path).stem)}_{time.strftime("%y%m%d_%H%M%S")}'
53
- pdf_data = read_fn(doc_path)
54
- if is_ocr:
55
- parse_method = 'ocr'
56
- else:
57
- parse_method = 'auto'
58
-
59
- if backend.startswith("vlm"):
60
- parse_method = "vlm"
61
- local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
62
- await aio_do_parse(
63
- output_dir=output_dir,
64
- pdf_file_names=[file_name],
65
- pdf_bytes_list=[pdf_data],
66
- p_lang_list=[language],
67
- parse_method=parse_method,
68
- end_page_id=end_page_id,
69
- p_formula_enable=formula_enable,
70
- p_table_enable=table_enable,
71
- backend=backend,
72
- server_url=url,
73
- )
74
- return local_md_dir, file_name
75
- except Exception as e:
76
- logger.exception(e)
77
-
78
-
79
- def compress_directory_to_zip(directory_path, output_zip_path):
80
- """
81
- 压缩指定目录到一个 ZIP 文件。
82
-
83
- :param directory_path: 要压缩的目录路径
84
- :param output_zip_path: 输出的 ZIP 文件路径
85
- """
86
- try:
87
- with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
88
-
89
- # 遍历目录中的所有文件和子目录
90
- for root, dirs, files in os.walk(directory_path):
91
- for file in files:
92
- # 构建完整的文件路径
93
- file_path = os.path.join(root, file)
94
- # 计算相对路径
95
- arcname = os.path.relpath(file_path, directory_path)
96
- # 添加文件到 ZIP 文件
97
- zipf.write(file_path, arcname)
98
- return 0
99
- except Exception as e:
100
- logger.exception(e)
101
- return -1
102
-
103
-
104
- def image_to_base64(image_path):
105
- with open(image_path, "rb") as image_file:
106
- return base64.b64encode(image_file.read()).decode('utf-8')
107
-
108
-
109
- def replace_image_with_base64(markdown_text, image_dir_path):
110
- # 匹配Markdown中的图片标签
111
- pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
112
-
113
- # 替换图片链接
114
- def replace(match):
115
- relative_path = match.group(1)
116
- full_path = os.path.join(image_dir_path, relative_path)
117
- base64_image = image_to_base64(full_path)
118
- return f"![{relative_path}](data:image/jpeg;base64,{base64_image})"
119
-
120
- # 应用替换
121
- return re.sub(pattern, replace, markdown_text)
122
-
123
-
124
- async def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=True, table_enable=True, language="ch", backend="pipeline", url=None):
125
- file_path = to_pdf(file_path)
126
- # 获取识别的md文件以及压缩包文件路径
127
- local_md_dir, file_name = await parse_pdf(file_path, './output', end_pages - 1, is_ocr, formula_enable, table_enable, language, backend, url)
128
- archive_zip_path = os.path.join('./output', str_sha256(local_md_dir) + '.zip')
129
- zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
130
- if zip_archive_success == 0:
131
- logger.info('压缩成功')
132
- else:
133
- logger.error('压缩失败')
134
- md_path = os.path.join(local_md_dir, file_name + '.md')
135
- with open(md_path, 'r', encoding='utf-8') as f:
136
- txt_content = f.read()
137
- md_content = replace_image_with_base64(txt_content, local_md_dir)
138
- # 返回转换后的PDF路径
139
- new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')
140
-
141
- return md_content, txt_content, archive_zip_path, new_pdf_path
142
 
143
 
144
- latex_delimiters = [
145
- {'left': '$$', 'right': '$$', 'display': True},
146
- {'left': '$', 'right': '$', 'display': False},
147
- {'left': '\\(', 'right': '\\)', 'display': False},
148
- {'left': '\\[', 'right': '\\]', 'display': True},
149
- ]
150
-
151
-
152
- with open("header.html", "r") as header_file:
153
- header = header_file.read()
154
-
155
-
156
- latin_lang = [
157
- 'af', 'az', 'bs', 'cs', 'cy', 'da', 'de', 'es', 'et', 'fr', 'ga', 'hr', # noqa: E126
158
- 'hu', 'id', 'is', 'it', 'ku', 'la', 'lt', 'lv', 'mi', 'ms', 'mt', 'nl',
159
- 'no', 'oc', 'pi', 'pl', 'pt', 'ro', 'rs_latin', 'sk', 'sl', 'sq', 'sv',
160
- 'sw', 'tl', 'tr', 'uz', 'vi', 'french', 'german'
161
- ]
162
- arabic_lang = ['ar', 'fa', 'ug', 'ur']
163
- cyrillic_lang = [
164
- 'rs_cyrillic', 'bg', 'mn', 'abq', 'ady', 'kbd', 'ava', # noqa: E126
165
- 'dar', 'inh', 'che', 'lbe', 'lez', 'tab'
166
- ]
167
- east_slavic_lang = ["ru", "be", "uk"]
168
- devanagari_lang = [
169
- 'hi', 'mr', 'ne', 'bh', 'mai', 'ang', 'bho', 'mah', 'sck', 'new', 'gom', # noqa: E126
170
- 'sa', 'bgc'
171
- ]
172
- other_lang = ['ch', 'ch_lite', 'ch_server', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka']
173
- add_lang = ['latin', 'arabic', 'east_slavic', 'cyrillic', 'devanagari']
174
-
175
- # all_lang = ['', 'auto']
176
- all_lang = []
177
- # all_lang.extend([*other_lang, *latin_lang, *arabic_lang, *cyrillic_lang, *devanagari_lang])
178
- all_lang.extend([*other_lang, *add_lang])
179
-
180
-
181
- def safe_stem(file_path):
182
- stem = Path(file_path).stem
183
- # 只保留字母、数字、下划线和点,其他字符替换为下划线
184
- return re.sub(r'[^\w.]', '_', stem)
185
-
186
-
187
- def to_pdf(file_path):
188
-
189
- if file_path is None:
190
- return None
191
-
192
- pdf_bytes = read_fn(file_path)
193
-
194
- # unique_filename = f'{uuid.uuid4()}.pdf'
195
- unique_filename = f'{safe_stem(file_path)}.pdf'
196
-
197
- # 构建完整的文件路径
198
- tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)
199
-
200
- # 将字节数据写入文件
201
- with open(tmp_file_path, 'wb') as tmp_pdf_file:
202
- tmp_pdf_file.write(pdf_bytes)
203
-
204
- return tmp_file_path
205
-
206
-
207
- def main():
208
- example_enable = True
209
-
210
  try:
211
- print("预初始化SgLang引擎...")
212
- from mineru.backend.vlm.vlm_analyze import ModelSingleton
213
- modelsingleton = ModelSingleton()
214
- predictor = modelsingleton.get_model(
215
- "sglang-engine",
216
- None,
217
- None,
218
- mem_fraction_static=0.5,
219
- enable_torch_compile=True,
220
- )
221
- print("SgLang引擎初始化完成")
 
 
 
 
 
 
222
  except Exception as e:
223
  logger.exception(e)
224
-
225
- with gr.Blocks() as demo:
226
- gr.HTML(header)
227
- with gr.Row():
228
- with gr.Column(variant='panel', scale=5):
229
- with gr.Row():
230
- suffixes = pdf_suffixes + image_suffixes
231
- input_file = gr.File(label='Please upload a PDF or image', file_types=suffixes)
232
- with gr.Row():
233
- max_pages = gr.Slider(1, 20, 10, step=1, label='Max convert pages')
234
- with gr.Row():
235
- backend = gr.Dropdown(["pipeline", "vlm-sglang-engine"], label="Backend", value="vlm-sglang-engine")
236
- with gr.Row(visible=False) as ocr_options:
237
- language = gr.Dropdown(all_lang, label='Language', value='ch')
238
- with gr.Row(visible=False) as client_options:
239
- url = gr.Textbox(label='Server URL', value='http://localhost:30000', placeholder='http://localhost:30000')
240
- with gr.Row(visible=False) as pipeline_options:
241
- is_ocr = gr.Checkbox(label='Force enable OCR', value=False)
242
- formula_enable = gr.Checkbox(label='Enable formula recognition', value=True)
243
- table_enable = gr.Checkbox(label='Enable table recognition(test)', value=True)
244
- with gr.Row():
245
- change_bu = gr.Button('Convert')
246
- clear_bu = gr.ClearButton(value='Clear')
247
- pdf_show = PDF(label='PDF preview', interactive=False, visible=True, height=800)
248
- if example_enable:
249
- example_root = os.path.join(os.path.dirname(__file__), 'examples')
250
- if os.path.exists(example_root):
251
- with gr.Accordion('Examples:'):
252
- gr.Examples(
253
- examples=[os.path.join(example_root, _) for _ in os.listdir(example_root) if
254
- _.endswith('pdf')],
255
- inputs=input_file
256
- )
257
-
258
- with gr.Column(variant='panel', scale=5):
259
- output_file = gr.File(label='convert result', interactive=False)
260
- with gr.Tabs():
261
- with gr.Tab('Markdown rendering'):
262
- md = gr.Markdown(label='Markdown rendering', height=1100, show_copy_button=True,
263
- latex_delimiters=latex_delimiters,
264
- line_breaks=True)
265
- with gr.Tab('Markdown text'):
266
- md_text = gr.TextArea(lines=45, show_copy_button=True)
267
-
268
-
269
- # 更新界面函数
270
- def update_interface(backend_choice):
271
- if backend_choice in ["vlm-transformers", "vlm-sglang-engine"]:
272
- return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
273
- elif backend_choice in ["vlm-sglang-client"]: # pipeline
274
- return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
275
- elif backend_choice in ["pipeline"]:
276
- return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)
277
- else:
278
- pass
279
-
280
-
281
- # 添加事件处理
282
- backend.change(
283
- fn=update_interface,
284
- inputs=[backend],
285
- outputs=[client_options, ocr_options, pipeline_options],
286
- api_name=False
287
- )
288
-
289
- input_file.change(fn=to_pdf, inputs=input_file, outputs=pdf_show, api_name=False)
290
- change_bu.click(fn=to_markdown, inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, language, backend, url],
291
- outputs=[md, md_text, output_file, pdf_show], api_name=False)
292
- clear_bu.add([input_file, md, pdf_show, md_text, output_file, is_ocr])
293
-
294
- demo.launch(ssr_mode=True)
295
-
296
-
297
- if __name__ == '__main__':
298
- main()
 
 
 
 
1
  import os
2
  import json
 
 
 
3
  from loguru import logger
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
 
6
+ if __name__ == '__main__':
7
+ os.system('pip uninstall -y mineru')
8
+ os.system('pip install git+https://github.com/myhloli/Magic-PDF.git@dev')
9
+ os.system('mineru-models-download -s huggingface -m vlm')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  try:
11
+ with open('/home/user/mineru.json', 'r+') as file:
12
+ config = json.load(file)
13
+
14
+ delimiters = {
15
+ 'display': {'left': '\\[', 'right': '\\]'},
16
+ 'inline': {'left': '\\(', 'right': '\\)'}
17
+ }
18
+
19
+ config['latex-delimiter-config'] = delimiters
20
+
21
+ if os.getenv('apikey'):
22
+ config['llm-aided-config']['title_aided']['api_key'] = os.getenv('apikey')
23
+ config['llm-aided-config']['title_aided']['enable'] = True
24
+
25
+ file.seek(0) # 将文件指针移回文件开始位置
26
+ file.truncate() # 截断文件,清除原有内容
27
+ json.dump(config, file, indent=4) # 写入新内容
28
  except Exception as e:
29
  logger.exception(e)
30
+ os.system('mineru-gradio --enable-sglang-engine true')