Python使用MinerU的簡(jiǎn)單的示例
1 簡(jiǎn)介
MinerU是國產(chǎn)的一款將PDF轉(zhuǎn)化為機(jī)器可讀格式的工具(如markdown、json),可以很方便地抽取為任意格式。目前支持圖像(.jpg及.png)、PDF、Word(.doc及.docx)、以及PowerPoint(.ppt及.pptx)等。
# 官網(wǎng)地址 https://mineru.readthedocs.io/en/latest/index.html # Github地址 https://github.com/opendatalab/mineru # API接口地址 https://mineru.readthedocs.io/en/latest/user_guide/quick_start/convert_pdf.html # 模型下載腳本地址 # 從ModelScope下載模型:download_models.py # 從HuggingFace下載模型: download_models_hf.py https://github.com/opendatalab/MinerU/tree/master/scripts
2 安裝MinerU
安裝Python環(huán)境
# 我的版本是:magic-pdf==1.1.0 pip install -U "magic-pdf[full]" -i https://pypi.tuna.tsinghua.edu.cn/simple
下載權(quán)重
官網(wǎng)提供了HuggingFace和ModelScope兩種方法下載,本文從ModlScope上下載,
# 官網(wǎng)下載方法地址 https://github.com/opendatalab/MinerU/blob/master/docs/how_to_download_models_zh_cn.md
開始下載權(quán)重
?? 注意:模型下載完成后,腳本會(huì)自動(dòng)生成用戶目錄下的magic-pdf.json文件,并自動(dòng)配置默認(rèn)模型路徑。 您可在【用戶目錄】下找到magic-pdf.json文件。
# 安裝modelscope pip install modelscope # 下載文件 wget https://gcore.jsdelivr.net/gh/opendatalab/MinerU@master/scripts/download_models.py -O download_models.py # 也可以到下面的地址,找到download_models.py下載 https://github.com/opendatalab/MinerU/tree/master/scripts # 執(zhí)行下載模型 # 為了方便使用模型,我修改了download_models.py,添加了設(shè)置模型的位置。 python download_models.py
修改后的download_models.py
?? 此步可以不做。
文件中的local_dir是我新加的下載模型的位置,如果不設(shè)置會(huì)下載到下面目錄中:windows的用戶目錄為 “C:\Users\用戶名”, linux用戶目錄為 “/home/用戶名”。
import json
import os
import requests
from modelscope import snapshot_download
def download_json(url):
# 下載JSON文件
response = requests.get(url)
response.raise_for_status() # 檢查請(qǐng)求是否成功
return response.json()
def download_and_modify_json(url, local_filename, modifications):
if os.path.exists(local_filename):
data = json.load(open(local_filename))
config_version = data.get('config_version', '0.0.0')
if config_version < '1.1.1':
data = download_json(url)
else:
data = download_json(url)
# 修改內(nèi)容
for key, value in modifications.items():
data[key] = value
# 保存修改后的內(nèi)容
with open(local_filename, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
if __name__ == '__main__':
mineru_patterns = [
"models/Layout/LayoutLMv3/*",
"models/Layout/YOLO/*",
"models/MFD/YOLO/*",
"models/MFR/unimernet_small_2501/*",
"models/TabRec/TableMaster/*",
"models/TabRec/StructEqTable/*",
]
# 設(shè)置模型下載的位置
local_dir="E:/mineru"
# 下載模型
model_dir = snapshot_download('opendatalab/PDF-Extract-Kit-1.0', allow_patterns=mineru_patterns, local_dir=local_dir)
layoutreader_model_dir = snapshot_download('ppaanngggg/layoutreader', local_dir=local_dir)
model_dir = model_dir + '/models'
print(f'model_dir is: {model_dir}')
print(f'layoutreader_model_dir is: {layoutreader_model_dir}')
json_url = 'https://gcore.jsdelivr.net/gh/opendatalab/MinerU@master/magic-pdf.template.json'
config_file_name = 'magic-pdf.json'
home_dir = os.path.expanduser('~')
config_file = os.path.join(home_dir, config_file_name)
json_mods = {
'models-dir': model_dir,
'layoutreader-model-dir': layoutreader_model_dir,
}
download_and_modify_json(json_url, config_file, json_mods)
print(f'The configuration file has been configured successfully, the path is: {config_file}')
3 Python使用MinerU
Python安裝完MinerU后,可以直接執(zhí)行下面的代碼,首次執(zhí)行時(shí)會(huì)自動(dòng)下載PaddleOCR模型的權(quán)重和參數(shù),PaddleOCR模型會(huì)自動(dòng)下載到用戶目錄下的.paddleocr目錄下。
解析PDF文件的Python代碼如下:
import os
from magic_pdf.data.data_reader_writer import FileBasedDataWriter, FileBasedDataReader
from magic_pdf.data.dataset import PymuDocDataset
from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
from magic_pdf.config.enums import SupportedPdfParseMethod
# pdf文件路徑
pdf_file_path = "E:/hello/test-5-2.pdf"
# 獲取沒有后綴的pdf文件名稱
pdf_file_path_without_suff = pdf_file_path.split(".")[0]
print(pdf_file_path_without_suff)
# 文件所在的目錄
pdf_file_path_parent_dir = os.path.dirname(pdf_file_path)
image_dir = os.path.join(pdf_file_path_parent_dir, "images")
print(image_dir)
# Markdown的寫入實(shí)例
# markdown_dir = "./output/markdown"
# writer_markdown = FileBasedDataWriter(markdown_dir)
writer_markdown = FileBasedDataWriter()
# 讀取圖片
writer_image = FileBasedDataWriter(image_dir)
# 讀取文件流
reader_pdf = FileBasedDataReader("")
bytes_pdf = reader_pdf.read(pdf_file_path)
# 處理數(shù)據(jù)
dataset_pdf = PymuDocDataset(bytes_pdf)
# 判斷是否支持ocr
if dataset_pdf.classify() == SupportedPdfParseMethod.OCR:
# 支持OCR
infer_result = dataset_pdf.apply(doc_analyze, ocr=True)
pipe_result = infer_result.pipe_ocr_mode(writer_image)
else:
# 不支持OCR
infer_result = dataset_pdf.apply(doc_analyze, ocr=False)
pipe_result = infer_result.pipe_txt_mode(writer_image)
# 在每一頁上都使用模型解析文本
infer_result.draw_model(pdf_file_path)
# 獲取模型處理后的結(jié)果
model_inference_result = infer_result.get_infer_res()
print(model_inference_result)
# 為pdf生成含有顏色標(biāo)注布局的pdf文件
pipe_result.draw_layout(f"{pdf_file_path_without_suff}_layout.pdf")
# 為pdf生成含有顏色標(biāo)注文本行的pdf文件
pipe_result.draw_span(f"{pdf_file_path_without_suff}_spans.pdf")
# 獲取markdown的內(nèi)容
markdown_content = pipe_result.get_markdown(image_dir)
print(markdown_content)
# 保存markdown文件
# pipe_result.dump_md(writer_markdown, f"{pdf_file_path_without_suff}.md", image_dir)
pipe_result.dump_md(writer_markdown, f"{pdf_file_path_without_suff}.md", image_dir)
# json文本列表
# 數(shù)據(jù)類型包括type、text、text_level、page_idx、img_path等
content_list_content = pipe_result.get_content_list(image_dir)
print(content_list_content)
# 保存json文本列表
pipe_result.dump_content_list(writer_markdown, f"{pdf_file_path_without_suff}_content_list.json", image_dir)
# 獲取含有位置信息的json文本
middle_json_content = pipe_result.get_middle_json()
# 保存含有位置信息的json文本
pipe_result.dump_middle_json(writer_markdown, f'{pdf_file_path_without_suff}_middle.json')到此這篇關(guān)于Python使用MinerU的簡(jiǎn)單的示例的文章就介紹到這了,更多相關(guān)Python使用MinerU內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python基礎(chǔ)之while循環(huán)語句的使用
這篇文章主要介紹了python基礎(chǔ)之while循環(huán)語句的使用,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們有一定的幫助,需要的朋友可以參考下2021-04-04
使用Pytorch Geometric進(jìn)行鏈接預(yù)測(cè)的實(shí)現(xiàn)代碼
PyTorch Geometric (PyG)是構(gòu)建圖神經(jīng)網(wǎng)絡(luò)模型和實(shí)驗(yàn)各種圖卷積的主要工具,在本文中我們將通過鏈接預(yù)測(cè)來對(duì)其進(jìn)行介紹,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2023-10-10
Python?dbm庫利用鍵值對(duì)存儲(chǔ)數(shù)據(jù)
Python中的dbm模塊提供了一種輕量級(jí)的數(shù)據(jù)庫管理工具,允許開發(fā)者使用鍵值對(duì)的形式存儲(chǔ)和檢索數(shù)據(jù),這篇文章將深入介紹dbm庫的使用,探討其基礎(chǔ)功能、高級(jí)特性以及實(shí)際應(yīng)用場(chǎng)景2023-12-12
Django框架教程之正則表達(dá)式URL誤區(qū)詳解
正則表達(dá)式對(duì)大家來說應(yīng)該都不陌生,下面這篇文章主要給大家介紹了關(guān)于Django框架教程之正則表達(dá)式URL誤區(qū)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01

