myhloli commited on
Commit
0cc1374
1 Parent(s): 2b79821
Files changed (2) hide show
  1. app.py +156 -0
  2. requirements.txt +21 -0
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Opendatalab. All rights reserved.
2
+
3
+ import base64
4
+ import os
5
+ import time
6
+ import zipfile
7
+ from pathlib import Path
8
+ import re
9
+
10
+ os.system('pip install -r requirements.txt --extra-index-url https://wheels.myhloli.com')
11
+ os.system('python -m pip install paddlepaddle-gpu==3.0.0b1 -i https://www.paddlepaddle.org.cn/packages/stable/cu118/')
12
+
13
+ from huggingface_hub import snapshot_download
14
+ model_dir = snapshot_download('opendatalab/PDF-Extract-Kit')
15
+
16
+ os.system('wget https://github.com/opendatalab/MinerU/raw/master/magic-pdf.template.json')
17
+ os.system('cp magic-pdf.template.json /root/magic-pdf.json')
18
+ os.system(f"sed -i 's|/tmp/models|{model_dir}/models|g' /root/magic-pdf.json")
19
+ # os.system("sed -i 's|cpu|cuda|g' /root/magic-pdf.json")
20
+
21
+ import gradio as gr
22
+ from loguru import logger
23
+
24
+ from magic_pdf.libs.hash_utils import compute_sha256
25
+ from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter
26
+ from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter
27
+ from magic_pdf.tools.common import do_parse, prepare_env
28
+
29
+
30
+ def read_fn(path):
31
+ disk_rw = DiskReaderWriter(os.path.dirname(path))
32
+ return disk_rw.read(os.path.basename(path), AbsReaderWriter.MODE_BIN)
33
+
34
+
35
+ def parse_pdf(doc_path, output_dir, end_page_id):
36
+ os.makedirs(output_dir, exist_ok=True)
37
+
38
+ try:
39
+ file_name = f"{str(Path(doc_path).stem)}_{time.time()}"
40
+ pdf_data = read_fn(doc_path)
41
+ parse_method = "auto"
42
+ local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
43
+ do_parse(
44
+ output_dir,
45
+ file_name,
46
+ pdf_data,
47
+ [],
48
+ parse_method,
49
+ False,
50
+ end_page_id=end_page_id,
51
+ )
52
+ return local_md_dir, file_name
53
+ except Exception as e:
54
+ logger.exception(e)
55
+
56
+
57
+ def compress_directory_to_zip(directory_path, output_zip_path):
58
+ """
59
+ 压缩指定目录到一个 ZIP 文件。
60
+
61
+ :param directory_path: 要压缩的目录路径
62
+ :param output_zip_path: 输出的 ZIP 文件路径
63
+ """
64
+ try:
65
+ with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
66
+
67
+ # 遍历目录中的所有文件和子目录
68
+ for root, dirs, files in os.walk(directory_path):
69
+ for file in files:
70
+ # 构建完整的文件路径
71
+ file_path = os.path.join(root, file)
72
+ # 计算相对路径
73
+ arcname = os.path.relpath(file_path, directory_path)
74
+ # 添加文件到 ZIP 文件
75
+ zipf.write(file_path, arcname)
76
+ return 0
77
+ except Exception as e:
78
+ logger.exception(e)
79
+ return -1
80
+
81
+
82
+ def image_to_base64(image_path):
83
+ with open(image_path, "rb") as image_file:
84
+ return base64.b64encode(image_file.read()).decode('utf-8')
85
+
86
+
87
+ def replace_image_with_base64(markdown_text, image_dir_path):
88
+ # 匹配Markdown中的图片标签
89
+ pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
90
+
91
+ # 替换图片链接
92
+ def replace(match):
93
+ relative_path = match.group(1)
94
+ full_path = os.path.join(image_dir_path, relative_path)
95
+ base64_image = image_to_base64(full_path)
96
+ return f"![{relative_path}](data:image/jpeg;base64,{base64_image})"
97
+
98
+ # 应用替换
99
+ return re.sub(pattern, replace, markdown_text)
100
+
101
+
102
+ def to_markdown(file_path, end_pages):
103
+ # 获取识别的md文件以及压缩包文件路径
104
+ local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1)
105
+ archive_zip_path = os.path.join("./output", compute_sha256(local_md_dir) + ".zip")
106
+ zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
107
+ if zip_archive_success == 0:
108
+ logger.info("压缩成功")
109
+ else:
110
+ logger.error("压缩失败")
111
+ md_path = os.path.join(local_md_dir, file_name + ".md")
112
+ with open(md_path, 'r', encoding='utf-8') as f:
113
+ txt_content = f.read()
114
+ md_content = replace_image_with_base64(txt_content, local_md_dir)
115
+ # 返回转换后的PDF路径
116
+ new_pdf_path = os.path.join(local_md_dir, file_name + "_layout.pdf")
117
+
118
+ return md_content, txt_content, archive_zip_path, show_pdf(new_pdf_path)
119
+
120
+
121
+ def show_pdf(file_path):
122
+ with open(file_path, "rb") as f:
123
+ base64_pdf = base64.b64encode(f.read()).decode('utf-8')
124
+ pdf_display = f'<embed src="data:application/pdf;base64,{base64_pdf}" ' \
125
+ f'width="100%" height="1000" type="application/pdf">'
126
+ return pdf_display
127
+
128
+
129
+ latex_delimiters = [{"left": "$$", "right": "$$", "display": True},
130
+ {"left": '$', "right": '$', "display": False}]
131
+
132
+ if __name__ == "__main__":
133
+ with gr.Blocks() as demo:
134
+ with gr.Row():
135
+ with gr.Column(variant='panel', scale=5):
136
+ file = gr.File(label="Please upload pdf", file_types=[".pdf"])
137
+ max_pages = gr.Slider(1, 10, 5, step=1, label="Max convert pages")
138
+ with gr.Row() as bu_flow:
139
+ change_bu = gr.Button("Convert")
140
+ clear_bu = gr.ClearButton([file, max_pages], value="Clear")
141
+ gr.Markdown(value="### PDF preview")
142
+ pdf_show = gr.HTML(label="PDF preview")
143
+
144
+ with gr.Column(variant='panel', scale=5):
145
+ output_file = gr.File(label="convert result", interactive=False)
146
+ with gr.Tabs():
147
+ with gr.Tab("Markdown rendering"):
148
+ md = gr.Markdown(label="Markdown rendering", height=1100, show_copy_button=True,
149
+ latex_delimiters=latex_delimiters, line_breaks=True)
150
+ with gr.Tab("Markdown text"):
151
+ md_text = gr.TextArea(lines=55, show_copy_button=True)
152
+ file.upload(fn=show_pdf, inputs=file, outputs=pdf_show)
153
+ change_bu.click(fn=to_markdown, inputs=[file, max_pages], outputs=[md, md_text, output_file, pdf_show])
154
+ clear_bu.add([md, pdf_show, md_text, output_file])
155
+
156
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ boto3>=1.28.43
2
+ Brotli>=1.1.0
3
+ click>=8.1.7
4
+ PyMuPDF>=1.24.9
5
+ loguru>=0.6.0
6
+ numpy>=1.21.6,<2.0.0
7
+ fast-langdetect==0.2.0
8
+ wordninja>=2.0.0
9
+ scikit-learn>=1.0.2
10
+ pdfminer.six==20231228
11
+ unimernet==0.1.6
12
+ matplotlib
13
+ ultralytics
14
+ paddleocr==2.7.3
15
+ paddlepaddle==3.0.0b1
16
+ pypandoc
17
+ struct-eqtable==0.1.0
18
+ detectron2
19
+ magic-pdf>=0.7.0b1
20
+ gradio
21
+ huggingface_hub