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
|
|
|
|
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 |
+
import uuid
|
10 |
+
import pymupdf
|
11 |
+
|
12 |
+
# os.system('pip install -U magic-pdf==0.10.5')
|
13 |
+
os.system('pip uninstall -y magic-pdf')
|
14 |
+
os.system('pip install git+https://github.com/opendatalab/MinerU.git@dev')
|
15 |
+
# os.system('pip install git+https://github.com/myhloli/Magic-PDF.git@dev')
|
16 |
+
|
17 |
+
os.system('wget https://github.com/opendatalab/MinerU/raw/master/scripts/download_models_hf.py -O download_models_hf.py')
|
18 |
+
os.system('python download_models_hf.py')
|
19 |
+
os.system("sed -i 's|cpu|cuda|g' /home/user/magic-pdf.json")
|
20 |
+
|
21 |
+
os.system('cp -r paddleocr /home/user/.paddleocr')
|
22 |
+
from gradio_pdf import PDF
|
23 |
+
|
24 |
+
import gradio as gr
|
25 |
+
from loguru import logger
|
26 |
+
|
27 |
+
from magic_pdf.libs.hash_utils import compute_sha256
|
28 |
+
from magic_pdf.rw.AbsReaderWriter import AbsReaderWriter
|
29 |
+
from magic_pdf.rw.DiskReaderWriter import DiskReaderWriter
|
30 |
+
from magic_pdf.tools.common import do_parse, prepare_env
|
31 |
+
|
32 |
+
|
33 |
+
def read_fn(path):
|
34 |
+
disk_rw = DiskReaderWriter(os.path.dirname(path))
|
35 |
+
return disk_rw.read(os.path.basename(path), AbsReaderWriter.MODE_BIN)
|
36 |
+
|
37 |
+
|
38 |
+
def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, layout_mode, formula_enable, table_enable, language):
|
39 |
+
os.makedirs(output_dir, exist_ok=True)
|
40 |
+
|
41 |
+
try:
|
42 |
+
file_name = f"{str(Path(doc_path).stem)}_{time.time()}"
|
43 |
+
pdf_data = read_fn(doc_path)
|
44 |
+
if is_ocr:
|
45 |
+
parse_method = "ocr"
|
46 |
+
else:
|
47 |
+
parse_method = "auto"
|
48 |
+
local_image_dir, local_md_dir = prepare_env(output_dir, file_name, parse_method)
|
49 |
+
do_parse(
|
50 |
+
output_dir,
|
51 |
+
file_name,
|
52 |
+
pdf_data,
|
53 |
+
[],
|
54 |
+
parse_method,
|
55 |
+
False,
|
56 |
+
end_page_id=end_page_id,
|
57 |
+
layout_model=layout_mode,
|
58 |
+
formula_enable=formula_enable,
|
59 |
+
table_enable=table_enable,
|
60 |
+
lang=language,
|
61 |
+
)
|
62 |
+
return local_md_dir, file_name
|
63 |
+
except Exception as e:
|
64 |
+
logger.exception(e)
|
65 |
+
|
66 |
+
|
67 |
+
def compress_directory_to_zip(directory_path, output_zip_path):
|
68 |
+
"""
|
69 |
+
压缩指定目录到一个 ZIP 文件。
|
70 |
+
|
71 |
+
:param directory_path: 要压缩的目录路径
|
72 |
+
:param output_zip_path: 输出的 ZIP 文件路径
|
73 |
+
"""
|
74 |
+
try:
|
75 |
+
with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
76 |
+
|
77 |
+
# 遍历目录中的所有文件和子目录
|
78 |
+
for root, dirs, files in os.walk(directory_path):
|
79 |
+
for file in files:
|
80 |
+
# 构建完整的文件路径
|
81 |
+
file_path = os.path.join(root, file)
|
82 |
+
# 计算相对路径
|
83 |
+
arcname = os.path.relpath(file_path, directory_path)
|
84 |
+
# 添加文件到 ZIP 文件
|
85 |
+
zipf.write(file_path, arcname)
|
86 |
+
return 0
|
87 |
+
except Exception as e:
|
88 |
+
logger.exception(e)
|
89 |
+
return -1
|
90 |
+
|
91 |
+
|
92 |
+
def image_to_base64(image_path):
|
93 |
+
with open(image_path, "rb") as image_file:
|
94 |
+
return base64.b64encode(image_file.read()).decode('utf-8')
|
95 |
+
|
96 |
+
|
97 |
+
def replace_image_with_base64(markdown_text, image_dir_path):
|
98 |
+
# 匹配Markdown中的图片标签
|
99 |
+
pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'
|
100 |
+
|
101 |
+
# 替换图片链接
|
102 |
+
def replace(match):
|
103 |
+
relative_path = match.group(1)
|
104 |
+
full_path = os.path.join(image_dir_path, relative_path)
|
105 |
+
base64_image = image_to_base64(full_path)
|
106 |
+
return f""
|
107 |
+
|
108 |
+
# 应用替换
|
109 |
+
return re.sub(pattern, replace, markdown_text)
|
110 |
+
|
111 |
+
|
112 |
+
def to_markdown(file_path, end_pages, is_ocr, layout_mode, formula_enable, table_enable, language):
|
113 |
+
# 获取识别的md文件以及压缩包文件路径
|
114 |
+
local_md_dir, file_name = parse_pdf(file_path, './output', end_pages - 1, is_ocr,
|
115 |
+
layout_mode, formula_enable, table_enable, language)
|
116 |
+
archive_zip_path = os.path.join("./output", compute_sha256(local_md_dir) + ".zip")
|
117 |
+
zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
|
118 |
+
if zip_archive_success == 0:
|
119 |
+
logger.info("压缩成功")
|
120 |
+
else:
|
121 |
+
logger.error("压缩失败")
|
122 |
+
md_path = os.path.join(local_md_dir, file_name + ".md")
|
123 |
+
with open(md_path, 'r', encoding='utf-8') as f:
|
124 |
+
txt_content = f.read()
|
125 |
+
md_content = replace_image_with_base64(txt_content, local_md_dir)
|
126 |
+
# 返回转换后的PDF路径
|
127 |
+
new_pdf_path = os.path.join(local_md_dir, file_name + "_layout.pdf")
|
128 |
+
|
129 |
+
return md_content, txt_content, archive_zip_path, new_pdf_path
|
130 |
+
|
131 |
+
|
132 |
+
latex_delimiters = [{"left": "$$", "right": "$$", "display": True},
|
133 |
+
{"left": '$', "right": '$', "display": False}]
|
134 |
+
|
135 |
+
|
136 |
+
def init_model():
|
137 |
+
from magic_pdf.model.doc_analyze_by_custom_model import ModelSingleton
|
138 |
+
try:
|
139 |
+
model_manager = ModelSingleton()
|
140 |
+
txt_model = model_manager.get_model(False, False)
|
141 |
+
logger.info(f"txt_model init final")
|
142 |
+
ocr_model = model_manager.get_model(True, False)
|
143 |
+
logger.info(f"ocr_model init final")
|
144 |
+
return 0
|
145 |
+
except Exception as e:
|
146 |
+
logger.exception(e)
|
147 |
+
return -1
|
148 |
+
|
149 |
+
|
150 |
+
model_init = init_model()
|
151 |
+
logger.info(f"model_init: {model_init}")
|
152 |
+
|
153 |
+
|
154 |
+
with open("header.html", "r") as file:
|
155 |
+
header = file.read()
|
156 |
+
|
157 |
+
|
158 |
+
latin_lang = [
|
159 |
+
'af', 'az', 'bs', 'cs', 'cy', 'da', 'de', 'es', 'et', 'fr', 'ga', 'hr',
|
160 |
+
'hu', 'id', 'is', 'it', 'ku', 'la', 'lt', 'lv', 'mi', 'ms', 'mt', 'nl',
|
161 |
+
'no', 'oc', 'pi', 'pl', 'pt', 'ro', 'rs_latin', 'sk', 'sl', 'sq', 'sv',
|
162 |
+
'sw', 'tl', 'tr', 'uz', 'vi', 'french', 'german'
|
163 |
+
]
|
164 |
+
arabic_lang = ['ar', 'fa', 'ug', 'ur']
|
165 |
+
cyrillic_lang = [
|
166 |
+
'ru', 'rs_cyrillic', 'be', 'bg', 'uk', 'mn', 'abq', 'ady', 'kbd', 'ava',
|
167 |
+
'dar', 'inh', 'che', 'lbe', 'lez', 'tab'
|
168 |
+
]
|
169 |
+
devanagari_lang = [
|
170 |
+
'hi', 'mr', 'ne', 'bh', 'mai', 'ang', 'bho', 'mah', 'sck', 'new', 'gom',
|
171 |
+
'sa', 'bgc'
|
172 |
+
]
|
173 |
+
other_lang = ['ch', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka']
|
174 |
+
|
175 |
+
all_lang = [""]
|
176 |
+
all_lang.extend([*other_lang, *latin_lang, *arabic_lang, *cyrillic_lang, *devanagari_lang])
|
177 |
+
|
178 |
+
|
179 |
+
def to_pdf(file_path):
|
180 |
+
with pymupdf.open(file_path) as f:
|
181 |
+
if f.is_pdf:
|
182 |
+
return file_path
|
183 |
+
else:
|
184 |
+
pdf_bytes = f.convert_to_pdf()
|
185 |
+
# 将pdfbytes 写入到uuid.pdf中
|
186 |
+
# 生成唯一的文件名
|
187 |
+
unique_filename = f"{uuid.uuid4()}.pdf"
|
188 |
+
|
189 |
+
# 构建完整的文件路径
|
190 |
+
tmp_file_path = os.path.join(os.path.dirname(file_path), unique_filename)
|
191 |
+
|
192 |
+
# 将字节数据写入文件
|
193 |
+
with open(tmp_file_path, 'wb') as tmp_pdf_file:
|
194 |
+
tmp_pdf_file.write(pdf_bytes)
|
195 |
+
|
196 |
+
return tmp_file_path
|
197 |
+
|
198 |
+
|
199 |
+
if __name__ == "__main__":
|
200 |
+
with gr.Blocks() as demo:
|
201 |
+
gr.HTML(header)
|
202 |
+
with gr.Row():
|
203 |
+
with gr.Column(variant='panel', scale=5):
|
204 |
+
file = gr.File(label="Please upload a PDF or image", file_types=[".pdf", ".png", ".jpeg", ".jpg"])
|
205 |
+
max_pages = gr.Slider(1, 10, 5, step=1, label="Max convert pages")
|
206 |
+
with gr.Row():
|
207 |
+
layout_mode = gr.Dropdown(["layoutlmv3", "doclayout_yolo"], label="Layout model", value="layoutlmv3")
|
208 |
+
language = gr.Dropdown(all_lang, label="Language", value="")
|
209 |
+
with gr.Row():
|
210 |
+
formula_enable = gr.Checkbox(label="Enable formula recognition", value=True)
|
211 |
+
is_ocr = gr.Checkbox(label="Force enable OCR", value=False)
|
212 |
+
table_enable = gr.Checkbox(label="Enable table recognition(test)", value=False)
|
213 |
+
with gr.Row():
|
214 |
+
change_bu = gr.Button("Convert")
|
215 |
+
clear_bu = gr.ClearButton(value="Clear")
|
216 |
+
pdf_show = PDF(label="PDF preview", interactive=True, height=800)
|
217 |
+
with gr.Accordion("Examples:"):
|
218 |
+
example_root = os.path.join(os.path.dirname(__file__), "examples")
|
219 |
+
gr.Examples(
|
220 |
+
examples=[os.path.join(example_root, _) for _ in os.listdir(example_root) if
|
221 |
+
_.endswith("pdf")],
|
222 |
+
inputs=pdf_show
|
223 |
+
)
|
224 |
+
|
225 |
+
with gr.Column(variant='panel', scale=5):
|
226 |
+
output_file = gr.File(label="convert result", interactive=False)
|
227 |
+
with gr.Tabs():
|
228 |
+
with gr.Tab("Markdown rendering"):
|
229 |
+
md = gr.Markdown(label="Markdown rendering", height=900, show_copy_button=True,
|
230 |
+
latex_delimiters=latex_delimiters, line_breaks=True)
|
231 |
+
with gr.Tab("Markdown text"):
|
232 |
+
md_text = gr.TextArea(lines=45, show_copy_button=True)
|
233 |
+
file.upload(fn=to_pdf, inputs=file, outputs=pdf_show)
|
234 |
+
change_bu.click(fn=to_markdown, inputs=[pdf_show, max_pages, is_ocr, layout_mode, formula_enable, table_enable, language],
|
235 |
+
outputs=[md, md_text, output_file, pdf_show], api_name=False)
|
236 |
+
clear_bu.add([file, md, pdf_show, md_text, output_file, is_ocr, table_enable, language])
|
237 |
+
|
238 |
+
demo.launch(ssr_mode=False)
|
header.html
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<html>
|
2 |
+
<head>
|
3 |
+
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css"> -->
|
4 |
+
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css">
|
5 |
+
<style>
|
6 |
+
.link-block {
|
7 |
+
border: 1px solid transparent;
|
8 |
+
border-radius: 24px;
|
9 |
+
background-color: rgba(54, 54, 54, 1);
|
10 |
+
cursor: pointer !important;
|
11 |
+
}
|
12 |
+
.link-block:hover {
|
13 |
+
background-color: rgba(54, 54, 54, 0.75) !important;
|
14 |
+
cursor: pointer !important;
|
15 |
+
}
|
16 |
+
.external-link {
|
17 |
+
display: inline-flex;
|
18 |
+
align-items: center;
|
19 |
+
height: 36px;
|
20 |
+
line-height: 36px;
|
21 |
+
padding: 0 16px;
|
22 |
+
cursor: pointer !important;
|
23 |
+
}
|
24 |
+
.external-link,
|
25 |
+
.external-link:hover {
|
26 |
+
cursor: pointer !important;
|
27 |
+
}
|
28 |
+
a {
|
29 |
+
text-decoration: none;
|
30 |
+
}
|
31 |
+
</style>
|
32 |
+
</head>
|
33 |
+
|
34 |
+
<body>
|
35 |
+
<div style="
|
36 |
+
display: flex;
|
37 |
+
flex-direction: column;
|
38 |
+
justify-content: center;
|
39 |
+
align-items: center;
|
40 |
+
text-align: center;
|
41 |
+
background: linear-gradient(45deg, #007bff 0%, #0056b3 100%);
|
42 |
+
padding: 24px;
|
43 |
+
gap: 24px;
|
44 |
+
border-radius: 8px;
|
45 |
+
">
|
46 |
+
<div style="
|
47 |
+
display: flex;
|
48 |
+
flex-direction: column;
|
49 |
+
align-items: center;
|
50 |
+
gap: 16px;
|
51 |
+
">
|
52 |
+
<div style="display: flex; flex-direction: column; gap: 8px">
|
53 |
+
<h1 style="
|
54 |
+
font-size: 48px;
|
55 |
+
color: #fafafa;
|
56 |
+
margin: 0;
|
57 |
+
font-family: 'Trebuchet MS', 'Lucida Sans Unicode',
|
58 |
+
'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
|
59 |
+
">
|
60 |
+
Document Scanner App by Lamipak R&D
|
61 |
+
</h1>
|
62 |
+
</div>
|
63 |
+
</div>
|
64 |
+
|
65 |
+
<p style="
|
66 |
+
margin: 0;
|
67 |
+
line-height: 1.6rem;
|
68 |
+
font-size: 16px;
|
69 |
+
color: #fafafa;
|
70 |
+
opacity: 0.8;
|
71 |
+
">
|
72 |
+
A one-stop, high-quality data extraction tool, supports
|
73 |
+
PDF/webpage/e-book extraction.<br>
|
74 |
+
</p>
|
75 |
+
<style>
|
76 |
+
.link-block {
|
77 |
+
display: inline-block;
|
78 |
+
}
|
79 |
+
.link-block + .link-block {
|
80 |
+
margin-left: 20px;
|
81 |
+
}
|
82 |
+
</style>
|
83 |
+
</div>
|
84 |
+
|
85 |
+
|
86 |
+
</body></html>
|