跳到内容

使用

转换

转换单个文档

要转换单个 PDF 文档,例如使用 convert()

from docling.document_converter import DocumentConverter

source = "https://arxiv.org/pdf/2408.09869"  # PDF path or URL
converter = DocumentConverter()
result = converter.convert(source)
print(result.document.export_to_markdown())  # output: "### Docling Technical Report[...]"

CLI

您也可以直接从命令行使用 Docling 转换单个文件(无论是本地文件还是通过 URL 获取的文件)或整个目录。

docling https://arxiv.org/pdf/2206.01062
您也可以通过 Docling CLI 使用 🥚SmolDocling 和其他 VLM
docling --pipeline vlm --vlm-model smoldocling https://arxiv.org/pdf/2206.01062
这将在支持的 Apple Silicon 硬件上使用 MLX 加速。

要查看所有可用选项(导出格式等),请运行 docling --help。更多详情请参见CLI 参考页面

高级选项

模型预取与离线使用

默认情况下,模型会在首次使用时自动下载。如果您希望为离线使用(例如在隔离环境中)明确预取模型,可以按如下步骤操作

步骤 1:预取模型

使用 docling-tools models download 工具

$ docling-tools models download
Downloading layout model...
Downloading tableformer model...
Downloading picture classifier model...
Downloading code formula model...
Downloading easyocr models...
Models downloaded into $HOME/.cache/docling/models.

或者,可以使用 docling.utils.model_downloader.download_models() 通过编程方式下载模型。

步骤 2:使用预取模型

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

artifacts_path = "/local/path/to/models"

pipeline_options = PdfPipelineOptions(artifacts_path=artifacts_path)
doc_converter = DocumentConverter(
    format_options={
        InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
    }
)

或使用 CLI

docling --artifacts-path="/local/path/to/models" FILE

或使用 DOCLING_ARTIFACTS_PATH 环境变量

export DOCLING_ARTIFACTS_PATH="/local/path/to/models"
python my_docling_script.py

使用远程服务

Docling 的主要目的是运行本地模型,这些模型不与远程服务共享任何用户数据。然而,仍然有一些有效的使用场景需要使用远程服务处理部分流水线,例如调用云厂商提供的 OCR 引擎或使用托管的 LLM。

在 Docling 中,我们决定允许使用此类模型,但要求用户明确选择与外部服务通信。

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

pipeline_options = PdfPipelineOptions(enable_remote_services=True)
doc_converter = DocumentConverter(
    format_options={
        InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
    }
)

如果未设置 enable_remote_services=True,系统将抛出异常 OperationNotAllowed()

注意:此选项仅与系统向远程服务发送用户数据有关。拉取数据(例如模型权重)的控制遵循模型预取与离线使用中描述的逻辑。

远程模型服务列表

此列表中的选项在处理文档时需要明确设置 enable_remote_services=True

  • PictureDescriptionApiOptions:通过 API 调用使用视觉模型。

调整流水线功能

示例文件 custom_convert.py 包含了多种调整转换流水线和功能的方法。

控制 PDF 表格提取选项

您可以控制表格结构识别是将识别到的结构映射回 PDF 单元格(默认)还是使用结构预测本身的文本单元格。如果您发现提取表格中的多列错误地合并为一列,这可以提高输出质量。

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

pipeline_options = PdfPipelineOptions(do_table_structure=True)
pipeline_options.table_structure_options.do_cell_matching = False  # uses text cells predicted from table structure model

doc_converter = DocumentConverter(
    format_options={
        InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
    }
)

自 docling 1.16.0 起:您可以控制想要使用哪种 TableFormer 模式。在 TableFormerMode.FAST(更快但准确率较低)和 TableFormerMode.ACCURATE(默认)之间选择,以处理复杂表格结构并获得更好的质量。

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

pipeline_options = PdfPipelineOptions(do_table_structure=True)
pipeline_options.table_structure_options.mode = TableFormerMode.ACCURATE  # use more accurate TableFormer model

doc_converter = DocumentConverter(
    format_options={
        InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)
    }
)

限制文档大小

您可以限制每个文档允许处理的文件大小和页数

from pathlib import Path
from docling.document_converter import DocumentConverter

source = "https://arxiv.org/pdf/2408.09869"
converter = DocumentConverter()
result = converter.convert(source, max_num_pages=100, max_file_size=20971520)

从二进制 PDF 流转换

您可以从二进制流而不是文件系统转换 PDF,如下所示

from io import BytesIO
from docling.datamodel.base_models import DocumentStream
from docling.document_converter import DocumentConverter

buf = BytesIO(your_binary_stream)
source = DocumentStream(name="my_doc.pdf", stream=buf)
converter = DocumentConverter()
result = converter.convert(source)

限制资源使用

您可以通过相应地设置环境变量 OMP_NUM_THREADS 来限制 Docling 使用的 CPU 线程数。默认设置为使用 4 个 CPU 线程。

使用特定的后端转换器

注意

本节讨论直接调用后端,即使用低级 API。仅在必要时才应这样做。在大多数情况下,使用如上文所述的 DocumentConverter(高级 API)就足够了 — 也是推荐的方式。

默认情况下,Docling 会尝试识别文档格式以应用适当的转换后端(参见支持的格式列表)。您可以将 DocumentConverter 限制为一组允许的文档格式,如多格式转换示例所示。或者,您也可以使用与文档内容匹配的特定后端。例如,您可以对 HTML 页面使用 HTMLDocumentBackend

import urllib.request
from io import BytesIO
from docling.backend.html_backend import HTMLDocumentBackend
from docling.datamodel.base_models import InputFormat
from docling.datamodel.document import InputDocument

url = "https://en.wikipedia.org/wiki/Duck"
text = urllib.request.urlopen(url).read()
in_doc = InputDocument(
    path_or_stream=BytesIO(text),
    format=InputFormat.HTML,
    backend=HTMLDocumentBackend,
    filename="duck.html",
)
backend = HTMLDocumentBackend(in_doc=in_doc, path_or_stream=BytesIO(text))
dl_doc = backend.convert()
print(dl_doc.export_to_markdown())

分块

您可以使用分块器(例如 HybridChunker)对 Docling 文档进行分块,如下所示(更多详细信息请查看此示例

from docling.document_converter import DocumentConverter
from docling.chunking import HybridChunker

conv_res = DocumentConverter().convert("https://arxiv.org/pdf/2206.01062")
doc = conv_res.document

chunker = HybridChunker(tokenizer="BAAI/bge-small-en-v1.5")  # set tokenizer as needed
chunk_iter = chunker.chunk(doc)

一个示例分块如下所示

print(list(chunk_iter)[11])
# {
#   "text": "In this paper, we present the DocLayNet dataset. [...]",
#   "meta": {
#     "doc_items": [{
#       "self_ref": "#/texts/28",
#       "label": "text",
#       "prov": [{
#         "page_no": 2,
#         "bbox": {"l": 53.29, "t": 287.14, "r": 295.56, "b": 212.37, ...},
#       }], ...,
#     }, ...],
#     "headings": ["1 INTRODUCTION"],
#   }
# }