MinerU 本地部署(GPU版)和测试使用 完整实践记录
一、环境说明
当前环境:
-
Windows
-
Python 虚拟环境:
uv -
GPU:NVIDIA
-
CUDA:已安装
-
使用目标:
- MinerU 本地解析 PDF
- 使用 GPU 加速
- 后续接入 RAG / 知识库系统
二、使用 uv 初始化项目
1. 创建项目
bash
uv init mineru
2. 进入项目目录
bash
cd mineru
3. 创建虚拟环境
bash
uv venv
4. 激活虚拟环境
Windows:
powershell
.venv\Scripts\activate
三、安装 MinerU
推荐安装:
bash
uv pip install -U "mineru[pipeline]"
说明:
-
pipeline:- OCR
- Layout
- 表格识别
- PDF结构化
-
适合:
- RAG
- 知识库
- PDF解析
四、下载模型
配置下载环境镜像modelscope:
bash
MINERU_MODEL_SOURCE=modelscope
执行:
bash
mineru-models-download 选择modelscope 下载pipeline
默认会下载到:
text
C:\Users\用户名\.cache\modelscope\hub\models\OpenDataLab\PDF-Extract-Kit-1___0
五、迁移模型到 D 盘
由于模型较大,因此将模型移动到:
text
D:\AI\modelscope
1. 关闭所有 Python / MinerU 进程
2. 移动目录
将:
text
C:\Users\用户名\.cache\modelscope\hub\models\OpenDataLab\PDF-Extract-Kit-1___0
移动到:
text
D:\AI\modelscope
六、修改 MinerU 配置
修改 MinerU 的配置 JSON 文件。
通常位置:
text
C:\Users\用户\mineru.json
修改模型路径为新的 D 盘目录。
七、替换 CPU 版 Torch 为 GPU 版
MinerU 默认可能安装 CPU 版 torch。
因此需要:
1. 卸载默认 torch
bash
pip uninstall torch torchvision torchaudio
2. 安装 CUDA GPU 版 torch
例如 CUDA 12.1:
bash
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
八、验证 GPU 是否可用
创建测试脚本:
python
import torch
print('torch=', torch.__version__)
print('cuda_runtime=', torch.version.cuda)
print('cuda_available=', torch.cuda.is_available())
print('gpu_name=', torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'None')
运行后示例:
text
torch= 2.7.0+cu121
cuda_runtime= 12.1
cuda_available= True
gpu_name= NVIDIA GeForce RTX 3060
说明 GPU 已成功启用。
九、编写 MinerU 测试脚本
创建:
text
pipeline_test.py
完整代码如下:
python
import os
import subprocess
from pathlib import Path
"""
脚本名称:pipeline_test.py
"""
def test_mineru_pipeline(
pdf_path: str,
output_dir: str,
method: str = "auto",
model_source: str = "local",
):
"""
使用 MinerU 的 CLI 测试单个 PDF 的 pipeline 解析。
method:
auto / txt / ocr
model_source:
local / modelscope / huggingface
"""
pdf = Path(pdf_path).expanduser().resolve()
out_dir = Path(output_dir).expanduser().resolve()
if not pdf.exists():
raise FileNotFoundError(f"PDF 不存在: {pdf}")
out_dir.mkdir(parents=True, exist_ok=True)
env = os.environ.copy()
env["MINERU_MODEL_SOURCE"] = model_source
mineru_exe = r"D:\software\mineru\.venv\Scripts\mineru.exe"
cmd = [
mineru_exe,
"-p", str(pdf),
"-o", str(out_dir),
"-b", "pipeline",
"-m", method,
]
print("即将执行命令:")
print(" ".join(f'"{x}"' if " " in x else x for x in cmd))
print(f"MINERU_MODEL_SOURCE={model_source}")
print("-" * 80)
result = subprocess.run(
cmd,
env=env,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
print("返回码:", result.returncode)
print("\n===== STDOUT =====")
print(result.stdout if result.stdout.strip() else "(无)")
print("\n===== STDERR =====")
print(result.stderr if result.stderr.strip() else "(无)")
print("\n===== 输出目录文件 =====")
if out_dir.exists():
for p in sorted(out_dir.rglob("*")):
print(p)
if result.returncode != 0:
raise RuntimeError("MinerU 执行失败,请检查上面的报错信息。")
if __name__ == "__main__":
# PDF 文件路径
pdf_path = r"C:\Users\Enty\Desktop\langchain短期 + 长期记忆架构-CSDN博客.pdf"
# 输出目录
output_dir = r"C:\Users\Enty\Desktop"
# auto:
# 自动识别 PDF 类型
#
# txt:
# 适合文本型 PDF
#
# ocr:
# 适合扫描件 PDF
test_mineru_pipeline(
pdf_path=pdf_path,
output_dir=output_dir,
method="auto",
model_source="local",
)
十、运行测试
执行:
bash
python pipeline_test.py
十一、输出结果
MinerU 会输出:
text
output/
├── markdown/
├── json/
├── images/
└── layout/
其中:
markdown
适合:
- RAG
- chunk
- embedding
json
包含:
- layout
- 段落结构
- 页码
- 坐标信息
适合:
- 高级知识库
- 可视化定位
- 文档追溯
十二、推荐知识库流程
推荐完整流程:
text
用户上传文件
↓
MinerU 解析
↓
Markdown / JSON
↓
结构化切片
↓
Embedding
↓
Milvus / FAISS
↓
RAG 检索
↓
LLM 回答
十三、推荐后续技术栈
推荐:
| 模块 | 推荐 |
|---|---|
| 文档解析 | MinerU |
| Embedding | Qwen Embedding |
| 向量库 | Milvus |
| Rerank | BGE-reranker |
| LLM | Qwen2.5-Instruct |
| Web框架 | FastAPI |
十四、经验总结
不推荐:
text
OCR → 纯文本 → 粗暴切片
因为:
- 上下文容易断裂
- 表格容易损坏
- PDF结构丢失
推荐:
text
结构化解析 → 按语义切片
即:
text
Section → Paragraph → Table
这是现代 RAG 的主流方案。