mineru从安装部署到测试使用完整指南

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 的主流方案。


相关推荐
安替-AnTi2 小时前
厚朴 APK 搜索接口分析
python·apk·解析·taobao
山川湖海2 小时前
AI时代快速学编程语言的陷阱(以Python为例)
大数据·人工智能·python
H Journey2 小时前
Supervisor 进程管理工具介绍
python·supervisor·linux 运维
春日见3 小时前
5分钟入门强化学习之动态规划算法与实现
大数据·人工智能·python·算法·机器学习·计算机视觉
DeniuHe3 小时前
sklearn 中所有交叉验证数据集划分方式完整总结
人工智能·python·sklearn
DeniuHe3 小时前
sklearn中不同交叉验证方法的场景适配
人工智能·python·sklearn
OCR_133716212754 小时前
技术解读:国内第一梯队 OCR 大模型现状与技术路线分析
ocr
隐于花海,等待花开4 小时前
16.Python 常用第三方库概览 深度解析
python
我材不敲代码4 小时前
Python 函数核心:位置参数与关键字参数详解
java·前端·python