mcpField
D
docling-document-intelligence

docling-document-intelligence

github.com/jr2804文档处理073 次安装8 周前更新
代码仓库

关于 docling-document-intelligence

docling-document-intelligence 是使用 Docling 解析、转换和检查文档的技能,面向需要提取文档内容或结构的用户。它支持本地文件和 URL,并结合 CLI 与 Python API,提供 OCR、分块及转换结果评估流程。

主要功能

  1. 01将 PDF、DOCX、PPTX、HTML 和图像转为 Markdown 或 JSON
  2. 02为扫描 PDF 自动启用 OCR
  3. 03以混合策略将文档切分为 RAG 区块
  4. 04检查标题、表格和图像结构
  5. 05评估转换质量并迭代调整流程

适用场景

  1. 01将扫描版 PDF 转为可读文本
  2. 02把文档转换成结构化 JSON
  3. 03为 RAG 准备按标题和 token 切分的内容
  4. 04检查表格缺失或复杂版面造成的转换问题

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jr2804/prompts --skill docling-document-intelligence

安装后在 Claude Code 中输入/docling-document-intelligence确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

EXAMPLE.md
improvement-log.md
pipelines.md
README.md
scripts/
docling-evaluate.py

详细介绍

Docling 文档智能技能

使用此技能解析、转换、分块,并分析文档结构和质量。 它既支持本地文件路径,也支持 URL,输出格式为 Markdown 或 结构化 JSON(DoclingDocument)。

转换使用 docling CLI(通过 uv tool install docling 安装)。 仅当 CLI 未提供相关功能时,才使用 Python API(分块、 VLM 远程 API 端点配置、混合 force_backend_text 模式)。

范围

任务支持情况
解析 PDF / DOCX / PPTX / HTML / 图像✅
转换为 Markdown✅
导出为 DoclingDocument JSON✅
为 RAG 分块(混合模式:标题 + 令牌)✅(Python API)
分析结构(标题、表格、图形)✅(Python API)
扫描版 PDF 的 OCR✅(自动启用)
多来源批量转换✅

分步说明

1. 确定输入

判断用户提供的是本地路径还是URL。 docling CLI 可直接接受这两种输入。

docling path/to/file.pdf
docling https://example.com/a.pdf
2. 选择流水线

Docling 有两类流水线。使用此表选择合适的流水线:

文档类型推荐流水线CLI 标志
原生数字 PDF(可选中文本)标准(默认)--pipeline standard
扫描版 / 仅图像 PDF标准 + OCR(自动)--pipeline standard
复杂版式、多栏、公式VLM--pipeline vlm
手写内容VLM--pipeline vlm

标准流水线——无需 GPU;速度快;会自动为扫描页面启用 OCR。 VLM 流水线——需要 GPU;速度较慢;对复杂版式和手写内容的保真度更高。

请参阅 pipelines.md,了解完整的决策矩阵、OCR 引擎表 (EasyOCR、RapidOCR、Tesseract、macOS)以及 VLM 模型预设。

3. 转换文档
CLI(适用于简单直接的转换,优先使用)
# --- Output format ---
docling report.pdf --output /tmp/                          # Markdown (default)
docling report.pdf --to json --output /tmp/               # JSON (structured)

# --- Pipeline selection ---
docling report.pdf --pipeline vlm --output /tmp/           # VLM for complex layouts
docling report.pdf --pipeline vlm --vlm-model granite_docling --output /tmp/  # VLM with specific model

# --- OCR options ---
docling report.pdf --ocr-engine tesserocr --output /tmp/  # Custom OCR engine
docling report.pdf --no-ocr --output /tmp/                # Disable OCR (speed)

# --- Speed / feature toggles ---
docling report.pdf --no-tables --output /tmp/             # Skip table extraction

# --- Remote VLM ---
docling report.pdf --pipeline vlm --enable-remote-services --output /tmp/

CLI 会将输出文件写入 --output 目录,并以输入文件命名(例如 report.pdf → report.md 或 report.json)。

CLI 参考: https://docling-project.github.io/docling/reference/cli/

Python API(适用于高级功能)

如果需要使用 CLI 未提供的功能,请使用 Python API: 分块、VLM 远程 API 端点配置或混合 force_backend_text 模式。

Docling 2.81+ API 说明: DocumentConverter(format_options=...) 接受 dict[InputFormat, FormatOption](例如 InputFormat.PDF → PdfFormatOption)。 使用 {"pdf": PdfPipelineOptions(...)} 这类字符串键会在运行时触发 AttributeError: 'PdfPipelineOptions' object has no attribute 'backend'。

标准流水线(默认):

from docling.document_converter import DocumentConverter, PdfFormatOption
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions

converter = DocumentConverter()
result = converter.convert("report.pdf")

converter = DocumentConverter(
    format_options={
        InputFormat.PDF: PdfFormatOption(
            pipeline_options=PdfPipelineOptions(do_ocr=True, do_table_structure=True),
        ),
    }
)
result = converter.convert("report.pdf")

VLM 流水线——本地(通过 HF Transformers 使用 GraniteDocling):

from docling.document_converter import DocumentConverter, PdfFormatOption
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import VlmPipelineOptions
from docling.datamodel import vlm_model_specs
from docling.pipeline.vlm_pipeline import VlmPipeline

pipeline_options = VlmPipelineOptions(
    vlm_options=vlm_model_specs.GRANITEDOCLING_TRANSFORMERS,
    generate_page_images=True,
)
converter = DocumentConverter(
    format_options={
        InputFormat.PDF: PdfFormatOption(
            pipeline_cls=VlmPipeline,
            pipeline_options=pipeline_options,
        )
    }
)
result = converter.convert("report.pdf")

VLM 流水线——远程 API(vLLM / LM Studio / Ollama):

此功能仅可通过 Python API 使用;CLI 不提供端点 URL、模型名称或 API 密钥配置。

from docling.document_converter import DocumentConverter, PdfFormatOption
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import VlmPipelineOptions
from docling.datamodel.pipeline_options_vlm_model import ApiVlmOptions, ResponseFormat
from docling.pipeline.vlm_pipeline import VlmPipeline

vlm_opts = ApiVlmOptions(
    url="http://localhost:8000/v1/chat/completions",
    params=dict(model="ibm-granite/granite-docling-258M", max_tokens=4096),
    prompt="Convert this page to docling.",
    response_format=ResponseFormat.DOCTAGS,
    timeout=120,
)
pipeline_options = VlmPipelineOptions(
    vlm_options=vlm_opts,
    generate_page_images=True,
    enable_remote_services=True,  # required — gates all outbound HTTP
)
converter = DocumentConverter(
    format_options={
        InputFormat.PDF: PdfFormatOption(
            pipeline_cls=VlmPipeline,
            pipeline_options=pipeline_options,
        )
    }
)
result = converter.convert("report.pdf")

混合模式(force_backend_text)——仅限 Python API:

对文本区域使用确定性 PDF 文本提取,同时通过 VLM 处理 图像和表格。可减少文本密集页面上的幻觉。

pipeline_options = VlmPipelineOptions(
    vlm_options=vlm_model_specs.GRANITEDOCLING_TRANSFORMERS,
    force_backend_text=True,
    generate_page_images=True,
)

所有情况下,result.document 都是一个 DoclingDocument 对象。

4. 选择输出格式

Markdown(默认,便于阅读):

docling report.pdf --to md --output /tmp/

或通过 Python:result.document.export_to_markdown()

JSON / DoclingDocument(结构化、无损):

docling report.pdf --to json --output /tmp/

或通过 Python:result.document.export_to_dict()

如果用户未指定格式,请询问:“要输出 Markdown 还是结构化 JSON(DoclingDocument)?”

5. 为 RAG 分块(混合策略)

分块仅可通过 Python API 使用。

默认:混合分块器——先按标题层级拆分,再根据 token 数拆分过大的章节。这样既能保留语义边界,又能遵循模型上下文限制。

docling-core 2.8.0 更改了分词器 API。请传入 BaseTokenizer 对象,而不是原始字符串:

HuggingFace 分词器(默认):

from docling.chunking import HybridChunker
from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizer

tokenizer = HuggingFaceTokenizer.from_pretrained(
    model_name="sentence-transformers/all-MiniLM-L6-v2",
    max_tokens=512,
)
chunker = HybridChunker(tokenizer=tokenizer, merge_peers=True)
chunks = list(chunker.chunk(result.document))

for chunk in chunks:
    embed_text = chunker.contextualize(chunk)
    print(chunk.meta.headings)  # heading breadcrumb list
    print(chunk.meta.origin.page_no)  # source page number

OpenAI 分词器(适用于 OpenAI 嵌入模型):

import tiktoken
from docling_core.transforms.chunker.tokenizer.openai import OpenAITokenizer

tokenizer = OpenAITokenizer(
    tokenizer=tiktoken.encoding_for_model("text-embedding-3-small"),
    max_tokens=8192,
)
# Requires: uv add 'docling-core[chunking-openai]'

有关分块策略和分词器的详细信息,请参阅 Docling 关于分块和 HybridChunker 的文档。

6. 分析文档结构

直接使用 DoclingDocument 对象检查结构:

doc = result.document

for item, level in doc.iterate_items():
    if hasattr(item, "label") and item.label.name == "SECTION_HEADER":
        print(f"{'#' * level} {item.text}")

for table in doc.tables:
    print(table.export_to_dataframe())  # pandas DataFrame
    print(table.export_to_markdown())

for picture in doc.pictures:
    print(picture.caption_text(doc))  # caption if present

完整的 API,请参阅 Docling 的结构和表格导出文档。

7. 评估输出并迭代(“尽力而为”转换的必需步骤)

每次转换后,只要用户关注保真度(而非快速预览),就要对 JSON 导出运行随附的评估器,然后根据需要优化处理流程。这是 Agent 检查工作并改进运行结果的方式,无需猜测。

步骤 A — 生成 JSON 和可选的 Markdown
docling "<source>" --to json --output /tmp/
docling "<source>" --to md --output /tmp/
步骤 B — 评估
uv run scripts/docling-evaluate.py /tmp/<filename>.json --markdown /tmp/<filename>.md

如果用户希望输出表格(发票、PDF 中的电子表格),请添加 --expect-tables。在 CI 风格的检查中,可使用 --fail-on-warn 收紧门槛。

该脚本会将 JSON 报告打印到 stdout,其中包含 status(pass | warn | fail)、metrics、issues 和 recommended_actions(建议后续尝试的具体 docling CLI 标志)。

步骤 C — 优化循环(最多尝试 3 次,除非用户另有要求)
  1. 如果 status 为 warn 或 fail,请根据 recommended_actions 应用一项主要更改(例如,切换到 --pipeline vlm、更改 --ocr-engine、确保已启用表格)。
  2. 使用 docling 重新转换,然后重新运行 uv run scripts/docling-evaluate.py。
  3. 当 status 为 pass 时停止;或在迭代 3 次后停止,然后向用户总结有效的方法和仍存在的问题。
步骤 D — 自我改进日志(技能记忆)

成功通过评估后或完成最后一次迭代后,在此技能目录中的 improvement-log.md 追加一条记录:

  • 源类型(例如,扫描 PDF、数字 PDF、DOCX)
  • 首次运行遇到的问题(来自 issues)
  • 修复或最有效缓解这些问题的处理流程和标志
  • 最终 status 以及一行主观质量说明

用户可以选择将此日志添加到 git 忽略列表;它用于本地学习,以便后续处理类似文档时能更快选用合适的处理流程。

8. Agent 质量检查清单(脚本不可用时手动检查)

如果无法运行 scripts/docling-evaluate.py,仍需检查以下内容:

检查项结果不佳时的操作
页数与源文档大致一致重新运行;如果布局复杂,尝试 --pipeline vlm
Markdown 并非接近空白启用 OCR / VLM
视觉上明显存在的表格缺失移除 --no-tables;尝试 --pipeline vlm
出现 \ufffd 替换字符更换 --ocr-engine 或使用 --pipeline vlm
同一行被重复多次使用 --pipeline vlm 或混合模式的 force_backend_text(Python API)

常见边缘情况

情况处理方法
扫描版 / 仅含图像的 PDF使用标准流程和 OCR,或使用 --pipeline vlm 以获得最佳质量
受密码保护的 PDF使用 --pdf-password PASSWORD;如果密码错误,将引发 ConversionError
超大型文档(500 页以上)使用标准流程,并添加 --no-tables 以提升速度
复杂布局 / 多栏使用 --pipeline vlm;标准流程可能会打乱阅读顺序
手写内容或公式仅使用 --pipeline vlm——标准 OCR 无法处理这些内容
需要身份验证的 URL先下载到临时文件;传入本地路径
含合并单元格的表格table.export_to_markdown() 可处理跨行跨列;VLM 通常更准确
非 UTF-8 编码Docling 会在内部进行规范化;无需特殊处理
VLM 幻觉生成文本通过 Python API 设置 force_backend_text=True 以使用混合模式
VLM API 调用受阻使用 --enable-remote-services(CLI)或 enable_remote_services=True(Python)
Apple Silicon使用 MLX 后端的 --vlm-model granite_docling,或使用 GRANITEDOCLING_MLX 预设(Python API)

流程参考

完整的决策矩阵、所有 OCR 引擎选项、VLM 模型预设和 API 服务配置:pipelines.md

输出约定

  • 始终报告页数和转换状态。
  • 如果评估属于任务范围,报告评估器的 status、主要 issues,以及最终输出由哪次优化尝试生成。
  • 对于 Markdown 输出:仅当用户需要复制粘贴时,才用围栏代码块包裹;否则直接呈现。
  • 对于 JSON 输出:除非用户另有说明,否则使用 indent=2 美化输出。
  • 对于分块:报告分块总数、Token 数量的最小值 / 最大值 / 平均值。
  • 对于结构分析:在深入细节前,概述标题层级结构、表格数量和图示数量。

依赖项

# Install the docling CLI as a uv tool
uv tool install docling
# For OpenAI tokenizer support, add to your project:
uv add 'docling-core[chunking-openai]'

检查已安装的版本(优先使用分发元数据——docling 可能未设置 __version__):

from importlib.metadata import version

print(version("docling"), version("docling-core"))

scripts/docling-evaluate.py 使用内联脚本元数据(PEP 723)声明自身依赖项——直接通过 uv run 运行,无需安装:

uv run scripts/docling-evaluate.py /tmp/report.json --markdown /tmp/report.md

示例

端到端操作示例,请参阅 EXAMPLE.md。

评论

支持 Markdown