1 つの文書を変換する#
API の出発点は DocumentConverter です。作成は軽く、モデルは最初の変換時に読み込まれて以後は再利用されるので、プロセス全体で 1 つのコンバーターを使い回しましょう。
from docling.document_converter import DocumentConverter
converter = DocumentConverter()
result = converter.convert("https://arxiv.org/pdf/2408.09869") # パス、URL、DocumentStream
print(result.status) # ConversionStatus.SUCCESS
doc = result.document # DoclingDocument
print(doc.export_to_markdown()[:300])convert() は ConversionResult を返します。document のほかに status・errors・pages・timings・confidence(ページごとの品質スコア)を持ち、信頼度の低いページを人の確認に回すのに使えます。
convert() の引数#
| 引数 | 既定値 | 働き |
|---|---|---|
source | — | Path、文字列のパスまたは URL、DocumentStream |
headers | None | source が URL のときの HTTP ヘッダー(認証トークンなど) |
raises_on_error | True | 失敗時に、失敗結果を返す代わりに例外を送出 |
max_num_pages | 無制限 | これより多いページ数の文書をスキップ |
max_file_size | 無制限 | このバイト数を超えるファイルをスキップ |
page_range | (1, ∞) | このページだけ変換(1 始まり・両端を含む)。例:(1, 10) |
progress_callback | None | 文書・フェーズ・ページ単位の進捗イベントを受け取る |
2.143.1 の DocumentConverter.convert のシグネチャから確認。convert_all() は同じ引数を取り、複数のソースを反復可能オブジェクトで渡します。
メモリ上のデータを変換する#
アップロード、S3 のオブジェクト、メール添付など、ファイルがバイト列で届く場合は DocumentStream で包みます。ファイル名の拡張子でバックエンドが決まります。
from io import BytesIO
from docling.datamodel.base_models import DocumentStream
from docling.document_converter import DocumentConverter
data = open("report.pdf", "rb").read() # S3 や API から得たバイト列など
stream = DocumentStream(name="report.pdf", stream=BytesIO(data))
doc = DocumentConverter().convert(stream).documentPDF パイプラインを設定する#
オプションは入力形式ごとに設定します。PDF(と画像)では、PdfPipelineOptions を PdfFormatOption で包みます。
from docling.datamodel.accelerator_options import AcceleratorOptions
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import (
PdfPipelineOptions, TableFormerMode, TableStructureOptions,
)
from docling.document_converter import DocumentConverter, PdfFormatOption
opts = PdfPipelineOptions()
opts.do_ocr = False # デジタル生成 PDF:当サイトの計測で 3.7 倍速
opts.do_table_structure = True
opts.table_structure_options = TableStructureOptions(mode=TableFormerMode.ACCURATE)
opts.accelerator_options = AcceleratorOptions(num_threads=8, device="auto")
opts.document_timeout = 300 # 秒。超えると途中までの結果を返す
converter = DocumentConverter(
format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=opts)}
)特に重要な既定値です(2.143.1 の PdfPipelineOptions のフィールドから取得)。
| オプション | 既定値 | メモ |
|---|---|---|
do_ocr | True | 既定モードでは PDF のテキスト層がない領域だけ OCR |
ocr_options | OcrAutoOptions() | インストール済みエンジンを自動選択(標準構成では RapidOCR) |
do_table_structure | True | TableFormer が行・列・結合セルを再構成 |
table_structure_options.mode | ACCURATE | FAST は当サイトの計測で全体 11% 高速 |
accelerator_options | 4 スレッド、device="auto" | auto は CUDA → Apple MPS → Intel XPU → CPU の順に選択 |
images_scale | 1.0 | 出力するページ画像・図の解像度 |
generate_page_images / generate_picture_images | False | 画像を出力する場合に必要 |
do_formula_enrichment / do_code_enrichment | False | 数式 → LaTeX、コードブロックの認識 |
do_picture_description / do_picture_classification | False | 追加モデルで図の説明文・種類を付与 |
do_chart_extraction | False | 棒・円・折れ線グラフ → 表 |
document_timeout | None | N 秒で文書の処理を打ち切る |
enable_remote_services | False | API ベースのモデルを使うには True が必要 |
artifacts_path | None | オフライン用のローカルモデルフォルダ |
OCR エンジンと言語は OCR ガイド、視覚言語パイプラインは VLM と Granite-Docling を参照してください。設定ビルダーでこのコードを自動生成できます。
壊れたファイルで止まらない一括変換#
convert_all() は結果を順に返すため、大きなフォルダでもメモリ使用量が増え続けません。raises_on_error=False にすると、壊れたファイルは例外ではなく失敗結果になります。
from pathlib import Path
from docling.datamodel.base_models import ConversionStatus
from docling.document_converter import DocumentConverter
converter = DocumentConverter()
files = sorted(Path("inbox").glob("*.pdf"))
out = Path("out"); out.mkdir(exist_ok=True)
for res in converter.convert_all(files, raises_on_error=False):
name = res.input.file.stem
if res.status in (ConversionStatus.SUCCESS, ConversionStatus.PARTIAL_SUCCESS):
res.document.save_as_markdown(out / f"{name}.md")
res.document.save_as_json(out / f"{name}.json")
else:
print(f"{name}: {res.status.value}", [e.error_message for e in res.errors])2.143.1 のステータスは pending・started・failure・success・partial_success・skipped です。partial_success は通常タイムアウトや一部ページの失敗を意味し、成功したページは文書に含まれます。
受け付ける形式を制限する#
from docling.datamodel.base_models import InputFormat
from docling.document_converter import DocumentConverter
converter = DocumentConverter(
allowed_formats=[InputFormat.PDF, InputFormat.DOCX, InputFormat.PPTX]
)それ以外の形式は変換されずに拒否されます。アップロード用のエンドポイントに便利です。36 種類の InputFormat の一覧は対応形式のページにあります。
DoclingDocument の中身#
DoclingDocument は木構造と、いくつかのフラットなリストでできています。各要素は label、テキストまたはデータ、prov(出典:ページ番号とバウンディングボックス)を持つので、回答をページ上の位置までたどれます。
| フィールド | 内容 |
|---|---|
texts | 段落、タイトル、見出し(level 付き)、リスト項目、キャプション、脚注、数式、コード |
tables | セルのグリッド(data.num_rows・data.num_cols・結合)を持つ TableItem |
pictures | 図。任意で分類と説明文 |
groups | リストや章などのコンテナ |
body / furniture | 本文の読み順ツリー / ヘッダー・フッター |
pages | ページサイズと(生成した場合)ページ画像 |
Docling 技術レポートを変換して得た実際の要素です。
{
"self_ref": "#/texts/2",
"label": "section_header",
"level": 1,
"text": "Version 1.0",
"prov": [{ "page_no": 1,
"bbox": { "l": 283.31, "t": 511.98, "r": 328.69, "b": 503.43,
"coord_origin": "BOTTOMLEFT" } }]
}for item, level in doc.iterate_items():
page = item.prov[0].page_no if item.prov else None
print(level, item.label, page, getattr(item, "text", "")[:60])表を pandas に#
for i, table in enumerate(doc.tables):
df = table.export_to_dataframe(doc=doc)
print(f"table {i}: {df.shape}")
df.to_csv(f"table_{i}.csv", index=False)doc=doc を渡すと、表がキャプションや参照を解決できます。テスト文書では Docling が 3 つの表を検出し、1 つ目は 4 × 8 のグリッドになりました。
出力形式#
| 欲しいもの | 呼び出し |
|---|---|
| Markdown 文字列 / ファイル | doc.export_to_markdown() / doc.save_as_markdown(path) |
| ロスレス JSON(再読み込み可) | doc.save_as_json(path) · 読み込みは DoclingDocument.load_from_json(path) |
| HTML | doc.export_to_html() / doc.save_as_html(path) |
| プレーンテキスト | doc.export_to_text() |
| Python の dict | doc.export_to_dict() |
| YAML | doc.save_as_yaml(path) |
| DocTags(VLM の学習・評価用) | doc.export_to_doctags() / doc.save_as_doctags(path) |
| WebVTT(音声・動画の字幕) | doc.export_to_vtt() / doc.save_as_vtt(path) |
| RAG 用チャンク | HybridChunker().chunk(doc)——RAG とチャンク化を参照 |
出力に画像を含める
Markdown・HTML・JSON は image_mode で画像の扱いを 3 通りから選べます。PLACEHOLDER(コメントで位置を示す・既定)、EMBEDDED(base64 で埋め込み)、REFERENCED(文書の隣に PNG を保存)です。画像は変換時に生成しておく必要があります。
from docling_core.types.doc import ImageRefMode
opts.generate_picture_images = True # 変換前に PdfPipelineOptions で設定
opts.images_scale = 2.0
...
doc.save_as_markdown("report.md", image_mode=ImageRefMode.REFERENCED)その他の入力形式#
Office・HTML・Markdown・多くの XML 形式は PDF パイプラインを通りません。ファイル自体の構造から直接解析されるため 1 秒もかからず、OCR やレイアウトモデルも不要です。画像は PDF と同じパイプライン、音声・動画は ASR パイプラインで処理されます。形式ごとの詳細は対応形式をご覧ください。
効果の大きい高速化のコツ#
- デジタル生成 PDF では OCR をオフに——当サイトの計測で最大の効果(1 ページ 8.5 → 2.3 秒)。
- コンバーターを使い回す。最初の変換にはモデルの読み込みが含まれます(同じ 9 ページでコールド 27.5 秒、ウォーム 20.8 秒)。
page_rangeを使う——分類などで最初の数ページだけ必要な場合。document_timeoutを設定して、1 つの異常なファイルがバッチ全体を止めないようにする。
詳しい数値はパフォーマンスガイドにあります。
よくある質問
Python で PDF を Markdown に変換するには?
DocumentConverter を作り、ファイルパスまたは URL で convert() を呼び、result.document.export_to_markdown() を呼びます。デジタル生成の PDF なら pipeline_options.do_ocr = False で大幅に高速化できます。
エラーで止まらずに多数のファイルを変換するには?
converter.convert_all(paths, raises_on_error=False) を使い、各 result.status(success・partial_success・failure・skipped)を確認します。
Docling で表を DataFrame として取り出すには?
result.document.tables をループし、table.export_to_dataframe(doc=result.document) を呼びます。pandas は標準の docling パッケージと一緒に入ります。
ディスクではなくメモリ上のファイルを変換できますか?
できます。DocumentStream(name='file.pdf', stream=BytesIO(data)) でバイト列を包み、convert() に渡します。ファイル名の拡張子で形式が決まります。
変換するページ数を制限するには?
convert() に page_range=(1, 10) を渡すか、max_num_pages で上限を超える文書をスキップします。
出典
- Docling ソース:docling/document_converter.py(2.143.1)
- Docling ソース:PdfPipelineOptions(docling/datamodel/pipeline_options.py)
- 公式ドキュメント:DoclingDocument の概念
- Docling 技術レポート(arXiv 2408.09869)