pdf-extractor-ai
Extract a PDF from bytes into one Docling document, optionally replace figures with summaries from a vision model you supply, then serialize that document to markdown.
The package does not download URLs and does not call a vision API. You pass PDF bytes, and you pass the model when you want summaries.
PDF bytes → PdfExtractor.extract → DoclingDocument
↓
summarize_images (optional)
↓
to_markdown
Reading order is newspaper order: physical page, then left-to-right column, then top to bottom. Headings become the tree. Text, lists, tables, and pictures that follow a heading are its children. A section that continues onto later pages is inserted only after those pages have been read.
Install
This project uses uv. In another project:
uv add pdf-extractor-ai onnxruntime
That installs this package, Docling, RapidOCR, and the other libraries they depend on. onnxruntime is the Linux OCR engine. pdf_extractor_download_models is then on PATH.
From a checkout of this repository:
uv sync
Run commands with uv run so they use that environment:
uv run python your_script.py
uv run pdf_extractor_download_models
Extract a PDF
extract returns a DoclingDocument. It does not call a vision model and it does not return markdown. do_ocr defaults to False. Pages that look like full-page scans (a bitmap covering most of the page) turn OCR on automatically: full-page OCR, Spanish/English language hints, and table cells take OCR text instead of a bad searchable overlay. Set do_ocr=True yourself for other OCR cases. Born-digital tables use do_cell_matching=False so TableFormer owns cell text.
from pdf_extractor_ai import PdfExtractor, document_title, to_markdown
pdf_bytes = open("report.pdf", "rb").read()
with PdfExtractor(num_workers=2) as extractor:
document = extractor.extract(pdf_bytes, name="report.pdf")
print(document_title(document, fallback="report.pdf"))
print(to_markdown(document))
num_workers threads share one queue. Each thread builds its own Docling converter on first use and keeps a private converter for each do_ocr value. Use the extractor as a context manager, or call shutdown() when you are done.
extract_async is the same job, awaited from an event loop:
document = await extractor.extract_async(pdf_bytes, do_ocr=False, max_pages=20)
max_pages stops after that many pages. An empty or unreadable PDF raises ValueError.
Markdown
to_markdown walks the document in tree order. Page banners stay open across a page and close when the next page starts, or at the end. A picture that was not summarized becomes <!-- image -->. Text that sits inside a picture box is left out. A summary block is written with its line breaks intact.
A section heading of level 1 is ##, because a document title uses # and each section level adds one more hash.
For a two-page report whose first heading is “Crop prospects” and whose second page starts “Regional outlook”, to_markdown returns:
========== page 1 start ==========
## Crop prospects
Global cereal production is expected to rise.
========== page 1 end ==========
========== page 2 start ==========
### Regional outlook
West Africa faces a rainfall deficit.
========== page 2 end ==========
document_title reads that tree. It prefers a page-1 title over a page-1 section heading, then the longest heading at that rank, then the first shallowest heading anywhere, then the fallback you pass. For the document above it returns Crop prospects.
split_pages returns the text inside each banner:
from pdf_extractor_ai import split_pages
pages = split_pages(markdown)
pages[1]
# '## Crop prospects\n\nGlobal cereal production is expected to rise.'
pages[2]
# '### Regional outlook\n\nWest Africa faces a rainfall deficit.'
is_low_text is true when the text, after banners and image placeholders are removed, is shorter than min_chars (default 200). The sample above is short, so is_low_text(markdown) is True and is_low_text(markdown, min_chars=40) is False.
layout_from_markdown maps those banners and headings onto line spans:
from pdf_extractor_ai.markdown import layout_from_markdown
layout = layout_from_markdown(markdown, document)
layout.document_title
# 'Crop prospects'
layout.sections[1].heading_path
# ('Crop prospects', 'Regional outlook')
layout.sections[1].page_start, layout.sections[1].page_end
# (2, 2)
Summarize figures
summarize_images runs after extract and before to_markdown. Group pictures by their parent heading and call your model once per section that has at least one picture. Sections with no pictures are skipped. The default concurrency is 3. The input document is left unchanged, and the function returns a new one.
Your model matches this protocol. visual_id values look like s0-v0. Return a map of those ids to summary text.
import asyncio
from pdf_extractor_ai import summarize_images, to_markdown
from pdf_extractor_ai.image_summarizer import SectionVisual, VisualLanguageModel
class GeminiCharts:
async def describe_section(
self,
*,
section_title: str,
section_text: str,
visuals: list[SectionVisual],
) -> dict[str, str]:
# section_text is the heading plus the other text in that section.
# visuals[i].png_bytes is a PNG crop. Send those to your vision API.
return {
visual.visual_id: "Cereal production rises through 2026."
for visual in visuals
}
async def main() -> None:
summarized = await summarize_images(
document,
GeminiCharts(),
model_name="gemini/gemini-3.7-flash",
)
print(to_markdown(summarized))
asyncio.run(main())
A successful summary replaces that picture with a text block. A missing id, an empty summary, or a raised error leaves the picture in place, so to_markdown still emits <!-- image --> for it.
By default, pictures that carry no information are not sent to your model. A picture smaller than 10,000 pixels is skipped. Otherwise Docling's document figure classifier labels it, and a picture labelled icon, photograph, logo, bar_code, qr_code, signature or stamp with confidence 0.6 or higher is skipped. Charts, maps, tables and diagrams are sent. Skipped pictures stay in place like failed ones, and a section whose pictures are all skipped makes no call. The classifier weights download from Hugging Face on first use. If the classifier fails, pictures are sent unfiltered. Pass picture_filter=PictureFilter(min_pixels=..., skip_classes=..., min_confidence=...) to change the rule, or picture_filter=None to send every picture.
Before a summary, a figure under the heading “Charts” looks like this:
========== page 1 start ==========
## Charts
Chart context
<!-- image -->
========== page 1 end ==========
After the call above, the same figure is the summary block. model_name, page, and bounding box come from the picture, and the last lines are the text your model returned:
========== page 1 start ==========
## Charts
Chart context
[Summarized Image: gemini/gemini-3.7-flash]
page: 1
bounding box: l=40.0, t=120.0, r=280.0, b=360.0 (TOPLEFT)
Summary:
Cereal production rises through 2026.
========== page 1 end ==========
Pictures whose shorter side is under 80 pixels are omitted during extraction.
Model weights
A container that sets HF_HUB_OFFLINE has to fetch weights while the network is still available. During the image build, install the dependencies and run the command before that variable is set:
uv add pdf-extractor-ai onnxruntime
pdf_extractor_download_models
Installing this package puts that command on PATH. In this repository, uv run pdf_extractor_download_models runs the same command. snapshot_download fills the Hugging Face cache. The revision argument has to be the same string Docling passes later. An offline lookup misses the cache when those strings differ. RapidOCR is not a Hugging Face repo, so HF_HUB_OFFLINE does not cover it. The command writes its ONNX files into RapidOCR's package models directory, which is where RapidOCR looks on the first scanned PDF.
The pins live in src/pdf_extractor_ai/download_models.py. They match the Docling version in uv.lock (2.150.0) and RapidOCR 3.10.0. Docling 2.150.1 requests the same three repositories and revisions. When you change the Docling version, update those pins in the script to the revisions that version requests. Reading them from the installed package:
- Layout. Preset
layout_heron_default, Transformers engine.docling.datamodel.stage_model_specsnamesdocling-project/docling-layout-heronat revisionmain. Use that repo. The ONNX engine override is a different repository, and this package uses the Transformers engine. - TableFormer.
extract()setsTableFormerMode.ACCURATE.TableStructureModel.download_modelsnamesdocling-project/docling-modelsat revisionv2.3.0. Download the whole repo. The accurate weights aremodel_artifacts/tableformer/accurateinside it. Layout and TableFormer load on the firstextract()call. - Picture classifier. Preset
document_figure_classifier_v2.DocumentPictureClassifierOptions.from_presetnamesdocling-project/DocumentFigureClassifier-v2.5at revisionmain. The default picture filter loads it when a picture has at least 10,000 pixels.extract()does not load it, and the PDF pipeline'sdo_picture_classificationstays off.
RapidOCR, from that release's default_models.yaml (onnxruntime). On Linux, with rapidocr and onnxruntime installed, OcrAutoOptions selects this engine. extract() builds that converter for do_ocr=True or a scanned PDF. Docling asks for Spanish first (iso:es) and uses that language only, because RapidOCR takes one language. Spanish and English share the PP-OCRv6 small checkpoints:
https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv6/det/PP-OCRv6_det_small.onnxhttps://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv6/rec/PP-OCRv6_rec_small.onnxhttps://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.10.0/onnx/PP-OCRv4/cls/ch_ppocr_mobile_v2.0_cls_mobile.onnx
When the RapidOCR version changes, replace those three URLs and their SHA-256 hashes in src/pdf_extractor_ai/download_models.py with the files the new release selects for that language.
docling-parse and pypdfium2 ship their binaries. Code and formula enrichment stay off, so docling-project/CodeFormulaV2 stays out of the script.
Development
See CHANGELOG.md for release notes.
uv sync
uv run ruff format
uv run ruff check
uv run mypy
uv run pytest
tests/test_pdf_visual_integration.py calls Gemini and is skipped unless GEMINI_API_KEY is in the environment. Pass the repo env file when you want that test to run:
uv run --env-file .env pytest
tests/test_per211232annx1.py loads Docling weights, auto-OCRs the scanned annex, and writes tests/test_data/per211232annx1.md. Needs an OCR engine Docling can select (on macOS, uv sync --group dev installs ocrmac). The default suite skips it. Run it with:
uv run pytest -m slow
The rest of the suite does not load Docling weights.
Performance and bounded processing
The non-OCR CPU pipeline initializes lazily on the first PDF and is reused. Conversion defaults to one page per bounded chunk after larger chunks increased measured peak memory. The existing document API keeps figure images; web-scout can use an internal text-only path. See the performance report for before/after timings, memory, regression coverage and benchmark commands.
Metadata
Release files for pdf-extractor-ai 0.3.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pdf_extractor_ai-0.3.4.tar.gz | 24.5 kB | Without provenance | Details for pdf_extractor_ai-0.3.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pdf_extractor_ai-0.3.4-py3-none-any.whl | Python 3 | none | any | Details for pdf_extractor_ai-0.3.4-py3-none-any.whl |
Total release size: 54.0 kB
Release files / pdf_extractor_ai-0.3.4.tar.gz
| Download URL | pdf_extractor_ai-0.3.4.tar.gz |
|---|---|
| Size | 24.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d33ddfcebcfbe3842e1d3506fc8ba15e28546d0497f86096c3dbfa104356bdc3
|
|
BLAKE2b-256 checksum How to use checksums |
48a0eb7060957458b5c47215ce60d92d9072e8ef7f715ed331aef798a77174ae
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.5
|
Release files / pdf_extractor_ai-0.3.4-py3-none-any.whl
| Download URL | pdf_extractor_ai-0.3.4-py3-none-any.whl |
|---|---|
| Size | 29.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5352c3739b87eb9ce44f86e91339231c89f8f8660ef40ac3da385082eceac59e
|
|
BLAKE2b-256 checksum How to use checksums |
e249756e2b0ce76fa7e6859903f1cae5a77251a1782e2eb61034640621c091b9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.5
|
Security for pdf-extractor-ai 0.3.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.