Metadata-Version: 2.5
Name: pypdftomd
Version: 0.4.5
Summary: Local-first Python library and CLI for converting PDFs into layout-aware Markdown
Project-URL: Homepage, https://pypi.org/project/pypdftomd/
Project-URL: Repository, https://github.com/MattBetancourt/pypdftomd
Project-URL: Documentation, https://github.com/MattBetancourt/pypdftomd#readme
Project-URL: Benchmarks, https://github.com/MattBetancourt/pypdftomd-bench
Project-URL: Changelog, https://github.com/MattBetancourt/pypdftomd/blob/main/CHANGELOG.md
Project-URL: Releases, https://github.com/MattBetancourt/pypdftomd/releases
Project-URL: Issues, https://github.com/MattBetancourt/pypdftomd/issues
Author-email: Matthew Betancourt <me@mattbetancourt.com>
License-Expression: AGPL-3.0-or-later
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Keywords: cli,document-parsing,extraction,llm,markdown,ocr,pdf,pdf-to-markdown,pymupdf,rag,table-extraction,tables
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Text Processing :: Filters
Classifier: Topic :: Text Processing :: Markup :: Markdown
Classifier: Topic :: Utilities
Requires-Python: >=3.12
Requires-Dist: pillow<14,>=12.0
Requires-Dist: pymupdf<3,>=2.2
Requires-Dist: pypdf<8,>=6.21.4
Provides-Extra: ocr-rapid
Requires-Dist: onnxruntime>=1.20; extra == 'ocr-rapid'
Requires-Dist: opencv-python-headless>=4.10; extra == 'ocr-rapid'
Requires-Dist: rapidocr<4,>=3.0; extra == 'ocr-rapid'
Provides-Extra: ocr-tesseract
Requires-Dist: pytesseract<1,>=0.3.13; extra == 'ocr-tesseract'
Description-Content-Type: text/markdown

# pypdftomd

Local-first Python library and CLI for converting PDFs into layout-aware Markdown.

[![PyPI](https://img.shields.io/pypi/v/pypdftomd?style=flat-square&color=334155)](https://pypi.org/project/pypdftomd/)
[![GitHub Release](https://img.shields.io/github/v/release/MattBetancourt/pypdftomd?style=flat-square&color=334155)](https://github.com/MattBetancourt/pypdftomd/releases)
[![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-1e293b?style=flat-square&logo=python&logoColor=cbd5e1)](https://www.python.org/downloads/)
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-475569?style=flat-square)](https://github.com/MattBetancourt/pypdftomd/blob/main/LICENSE)
[![Packaging CI](https://img.shields.io/github/actions/workflow/status/MattBetancourt/pypdftomd/ci.yml?style=flat-square&label=ci&branch=main)](https://github.com/MattBetancourt/pypdftomd/actions/workflows/ci.yml)

[Quickstart](#quickstart) · [Benchmarks](#benchmarks-and-trade-offs) · [Architecture](#architecture) · [Output](#what-the-output-looks-like) · [Install](#install) · [Agent skill](#coding-agent-skill) · [Usage](#usage) · [Limitations](#limitations) · [Changelog](https://github.com/MattBetancourt/pypdftomd/blob/main/CHANGELOG.md) · [License](#license)

## Overview

pypdftomd converts digital PDFs into structured Markdown on local CPU using deterministic PyMuPDF geometry for RAG ingestion and privacy-sensitive document pipelines.

- **Deterministic CPU geometry:** Reconstructs multi-column reading order, headings, lists, and tables directly from embedded PDF geometry without external APIs, GPUs, or neural layout models.
- **Fail-loud reliability signals:** Emits inline `<!-- extraction-warning: ... -->` HTML comments and `stderr` summaries whenever Type3 fonts, unmapped glyphs, chart grids, or OCR failures make page content unreliable.
- **Native link and math-font fidelity:** Preserves external HTTP(S) PDF annotations as Markdown links, decodes baseline-shifted superscripts/subscripts to Unicode, and handles TeX/AMS math font families.
- **Opt-in local OCR and preflight routing:** Inspects encryption and page text quality via `--analyze` and `--metadata`, with selective whole-page OCR fallback via local Tesseract or RapidOCR.

## Quickstart

Requires Python 3.12 or newer.

```sh
# Run without installing permanently
uvx pypdftomd report.pdf

# Or install the CLI and Python library with pip
pip install pypdftomd
```

```python
from pathlib import Path
from pypdftomd import extract_text_from_pdf

markdown = extract_text_from_pdf(Path("report.pdf"))
```

## Benchmarks and trade-offs

Full 200-document [OpenDataLoader benchmark](https://github.com/opendataloader-project/opendataloader-bench) quality scores (`200` NID, `42` TEDS, `107` MHS; zero missing predictions; `0` to `1`, higher is better; column leaders in bold). Quality scores only; runtime and memory depend on document layout and worker count.

| Extractor | Models / Runtime | Overall | NID | NID-S | TEDS | TEDS-S | MHS | MHS-S |
|---|---|---:|---:|---:|---:|---:|---:|---:|
| **pypdftomd 0.4.0** | None (text-layer, PyMuPDF) | **0.902** | **0.926** | **0.928** | 0.845 | 0.861 | **0.850** | **0.913** |
| Docling 2.155.0 | Heron + TableFormer + RapidOCR (CPU) | 0.892 | 0.906 | 0.859 | **0.925** | **0.944** | 0.830 | 0.905 |
| Liteparse 2.21.5 | None (text-layer, PDFium) | 0.891 | 0.918 | 0.922 | 0.823 | 0.841 | 0.838 | 0.901 |
| OpenDataLoader hybrid 2.5.24 | JRE + Docling + EasyOCR (CPU) | 0.880 | 0.920 | 0.910 | 0.676 | 0.911 | 0.823 | 0.888 |
| pdf-inspector 1.27.0 | None (text-layer, Rust) | 0.870 | 0.911 | 0.901 | 0.800 | 0.842 | 0.777 | 0.859 |
| OpenDataLoader plain 2.5.24 | None (JRE rules) | 0.843 | 0.913 | 0.917 | 0.483 | 0.506 | 0.757 | 0.837 |

<details>
<summary>Benchmark pins, metric definitions, and peer settings</summary>

- **Corpus and evaluator pins:** `opendataloader-bench` commit `7af1d8f4d0c09f51ea1a5c6ba5f66e993286d109`, evaluator digest `99c22bd79c2fe4ada21c86c57f4ddc174a8c862f59a41f7d6635d31ce7a22942`. Full-corpus rows cover the same 200 PDFs with zero missing predictions (`200` NID/NID-S, `42` reference-table TEDS/TEDS-S, `107` MHS/MHS-S).
- **pypdftomd 0.4.0 configuration:** `ocr_fallback=False`, `cache_dir=None`, `page_breaks=False`, `workers=1` on PyMuPDF 2.2 (verified 2026-12-02 on the full 200-PDF corpus with zero byte diffs across repeated runs; 1 false table). Peer rows use pinned releases from a frozen peer comparison under their recorded extraction settings (including model and OCR differences where enabled), comparing as-run output quality rather than isolating a single mechanism.
- **Metrics (0 to 1, higher is better):** **Overall** is the per-document mean of available NID, TEDS, and MHS scores averaged across all 200 documents (not the mean of the three column means). **NID** measures normalized text sequence similarity across the full Markdown output; **NID-S** measures the same text comparison after removing tables. **TEDS** measures table structure and cell text similarity; **TEDS-S** measures table structure without cell text. **MHS** measures heading and content grouping similarity, and **MHS-S** measures that grouping structure without text; the evaluator treats all heading levels (`#`, `##`, etc.) as equivalent.
- **Partial and separate peer runs (not ranked above):** **Marker 2.0.0** was evaluated only on a 68-document hard subset (42 TEDS, 36 MHS) and cannot be ranked against full-corpus rows. **PyMuPDF4LLM 2.1** was evaluated separately in a pairwise 200-document comparison against an earlier baseline on the same corpus and evaluator and was not rerun on 0.4.0.
- **Peer settings:** Docling (`DocumentConverter().convert(...).document.export_to_markdown()`, native text plus conditional OCR) and OpenDataLoader hybrid (`hybrid='docling-fast'` with Docling 2.155.0 CPU backend, 97/200 routed) ran on CPU with layout and table models. Liteparse (`ocr` off, `extract_links` false), pdf-inspector, and OpenDataLoader plain (`table_method='cluster'`) ran rule-based extraction without models.

</details>

### When to use pypdftomd

| Workload | Recommended path |
|---|---|
| Digital reports, papers, and multi-column PDFs | Default native mode (`pypdftomd report.pdf -o report.md`) |
| Unknown or mixed digital/scanned batches | Preflight with `--analyze`, then extract with `--ocr-fallback` |
| High-throughput text and tables without heading reflow | Fast mode (`--fast`) |
| Heavy borderless/multi-span tables or degraded scans | Consider neural layout models such as Docling |

- **Where pypdftomd works well:** Leads all full-corpus peers on **Overall (0.902)**, **NID (0.926)**, **NID-S (0.928)**, **MHS (0.850)**, and **MHS-S (0.913)** using CPU geometry alone — ahead of Docling (0.892) without neural layout models, model weight downloads, or a GPU. Preserving native HTTP(S) links as `[label](url)` carries a small measured NID cost because the evaluator counts link syntax as text difference—a trade-off accepted for link fidelity.
- **Where peers lead:** **Docling 2.155.0** leads on **TEDS (0.925 vs. 0.845)** and **TEDS-S (0.944 vs. 0.861)**, and **OpenDataLoader hybrid 2.5.24** leads on **TEDS-S (0.911 vs. 0.861)**; neural table-structure models outperform rule-based grids on borderless, multi-span, and tight-gutter layouts. Region-level OCR and semantic heading models also outperform whole-page OCR fallback and font-tier heuristics on scanned pages and unstyled headings.

Rerun every score above from pinned versions with the [benchmark reproduction repository](https://github.com/MattBetancourt/pypdftomd-bench) (verified at commit [`945b64b`](https://github.com/MattBetancourt/pypdftomd-bench/commit/945b64be450806366b95822d571d1564b4b2d1e3); pinned dependencies and evaluation scripts, without redistributing third-party corpus PDFs).

## Architecture

Each page runs through a region-first pipeline so tables, figures, equations, and prose claim words exclusively before Markdown assembly:

```text
Preflight & Page Selection ─▶ Single-Pass Page Geometry ─▶ Region Typing
  ─▶ Exclusive Word Ownership ─▶ Region Interpretation ─▶ Reading-Order Flow & Emission
                                                               │
                                                 (opt-in --ocr-fallback)
                                                               ▼
                                                        Local OCR Merge
```

| Element | Mechanism |
|---|---|
| **Headings** | Document-wide font-tier clustering with bold/TeX-bold detection, numbered-sequence and sidebar promotion, and heading vetoes for captions, lists, TOC entries, and prose fragments. |
| **Multi-column reading order** | Recursive layout cuts (`GUTTER_EM` gutters), column splitting with untouched-order preservation, and unified reading-order flow across regions. |
| **Tables** | Detects stroked frames, painted fill/shading rules, booktabs rule bands, and aligned borderless runs; one page analysis feeds both inline GFM tables and CSV/bbox exports. |
| **Math and scripts** | Identifies TeX/AMS/Symbol math fonts (`cmmi`, `cmsy`, `cmex`, `msam`, `msbm`, `texcm`, `math`, `symbol`, `standardsyml`), remaps malformed `TeXCMMathsSymbols` operators, and converts baseline-shifted or flagged runs to Unicode superscripts/subscripts. |
| **Native links** | Maps external HTTP(S) PDF link annotations onto decoded word spans as Markdown `[label](url)` links. |
| **Figures and vector art** | Filters raster icons smaller than 30 units, bounds vector-path inspection so complex drawings do not stall text extraction, and exports clustered dense vector figures as cropped PNGs when `--images-output` is set. |

## What the output looks like

With `--include-summary`, line 1 records a machine-readable verdict alongside 1-indexed page markers, inline GFM tables, preserved links, Unicode scripts, and fail-loud page warnings:

```markdown
<!-- extraction-summary: pages_with_warnings=[2] warning_counts={unmapped_glyphs:1} -->

<!-- Page 1 -->

## Quarterly Summary

Revenue rose 12 percent under the [Q4 filing](<https://example.com/q4>) with variance σ² ≤ 0.04 across sites

| Region | Units | Margin |
| --- | --- | --- |
| North | 1,420 | 31.4% |
| South | 1,185 | 28.9% |

---

<!-- Page 2 -->

<!-- extraction-warning: page contains 1 block(s) with unmapped glyphs (font lacks ToUnicode mapping; renderer shows �); equations/tables on this page may be corrupt — visually verify against the rendered page image -->

Appendix notes with partial glyph decoding.
```

<details>
<summary>In-band warning keys</summary>

`warning_counts` counts pages carrying each key (never body-prose lookalikes, which are backslash-escaped on assembly):

- `type3` — Page uses a Type3 font lacking a usable `/ToUnicode` map.
- `unmapped_glyphs` — One or more text blocks contain unresolved glyph replacement characters (`\ufffd`).
- `chart_grid_table` — Table was reconstructed over chart-like vector marks; cell associations may be unreliable.
- `low_confidence` — Local OCR returned low recognition confidence.
- `empty_ocr` — Local OCR produced no readable text on an image-only or unreadable page.
- `ocr_timeout` — OCR timed out or failed on the page; embedded text was retained.
- `ocr_page_render_failed` — OCR could not load or render the page.
- `ocr_backend_unavailable` — Requested OCR backend is missing; embedded text was retained.
- `embedded_extraction_failed` — Embedded page text extraction failed; page content is incomplete.
- `table_detection_failed` — Table detection failed on the page; prose-only fallback was kept.

</details>

## Install

pypdftomd is published on [PyPI](https://pypi.org/project/pypdftomd/) and [GitHub Releases](https://github.com/MattBetancourt/pypdftomd/releases), and requires Python 3.12 or newer.

Run ephemerally or install the CLI with [uv](https://docs.astral.sh/uv/getting-started/installation/):

```sh
# Run without installing permanently
uvx pypdftomd report.pdf
uvx --from 'pypdftomd[ocr-tesseract]' pypdftomd report.pdf --ocr-fallback

# Install the CLI tool globally
uv tool install pypdftomd
pypdftomd --help
```

If `pypdftomd` is not on your PATH after `uv tool install`, run `uv tool update-shell` and restart your shell. To install the Python library or CLI with `pip`:

```sh
pip install pypdftomd

# Optional local OCR backends
pip install "pypdftomd[ocr-tesseract]"
pip install "pypdftomd[ocr-rapid]"
```

<details>
<summary>GitHub Releases wheel fallback, source checkout, and OCR prerequisites</summary>

- **GitHub Releases wheel:** Download `pypdftomd-<version>-py3-none-any.whl` from [GitHub Releases](https://github.com/MattBetancourt/pypdftomd/releases) and install with `pip install ./pypdftomd-<version>-py3-none-any.whl` or `uv tool install --python 3.12 <wheel-url>`.
- **Source checkout:** Run `pip install .` (or `pip install ".[ocr-tesseract]"` / `pip install ".[ocr-rapid]"`).
- **Tesseract (`[ocr-tesseract]`):** Requires the `tesseract` binary on `PATH` or the `TESSERACT_CMD` environment variable pointing to the executable.
- **RapidOCR (`[ocr-rapid]`):** Installs `rapidocr`, `onnxruntime`, and `opencv-python-headless` for detection-first PP-OCRv6; useful on photo pages or sparse captions, weaker on dense equations.

</details>

### Coding agent skill

Install the [pypdftomd skill](https://github.com/MattBetancourt/pypdftomd/blob/main/skills/pypdftomd/SKILL.md) in a coding agent that supports
the [Agent Skills format](https://agentskills.io/specification):

```sh
gh skill install MattBetancourt/pypdftomd pypdftomd
npx skills add MattBetancourt/pypdftomd --skill pypdftomd
```

For a manual install, copy the `skills/pypdftomd` folder into your agent's skill
directory. Use `.agents/skills/` in the project for Codex or `.claude/skills/`
for Claude Code. Make sure `pypdftomd` (or `uvx pypdftomd`) is runnable in the
environment the agent uses to run commands.

Try asking your agent, “Use the pypdftomd skill to convert pages 3–7 of
`report.pdf` to `report.md`.”

## Usage

### CLI

```sh
# Extract Markdown to stdout or a file
pypdftomd report.pdf
pypdftomd report.pdf -o report.md

# Select pages, tune workers, and enable selective OCR fallback
pypdftomd report.pdf --pages 1-5 --workers 2 --ocr-fallback -o report.md

# Process a directory tree, or emit structured reports for several PDFs
pypdftomd ./incoming --recursive --output-dir ./reports
pypdftomd first.pdf second.pdf --json

# Check the selected local OCR backend before processing
pypdftomd --check-ocr --ocr-engine rapid

# Export images, contact sheet, and CSV tables in one run
pypdftomd report.pdf --images-output ./images --contact-sheet sheet.png --tables-output ./tables -o report.md
```

| Flag | Effect |
|---|---|
| `-o`, `--output PATH` | Write UTF-8 LF Markdown for one PDF to `PATH` (default: `stdout`); `-o -` explicitly selects stdout. |
| `-r`, `--recursive` | Include nested PDFs in directory inputs; without it, only direct PDF children are selected. |
| `--output-dir DIR` | Write a source-qualified Markdown or JSON report per PDF; required for multi-PDF Markdown. Mutually exclusive with `-o`. |
| `--json` | Emit structured reports with Markdown, page and warning details (including `failed_pages` for pages with embedded extraction, OCR render, or OCR timeout/failure warnings), and artifact paths. Multi-PDF stdout contains a `documents` array. |
| `-q`, `--quiet` | Suppress incidental status and batch summary lines while retaining primary output and diagnostics. |
| `--fail-on-warning` | Publish outputs and exit 3 if any extracted document has a page warning; hard errors exit 1. |
| `-V`, `--version` | Print the version and exit. |
| `--pages SPEC` | 1-indexed page selection, e.g. `1-3,7` (default: all pages). |
| `-w`, `--workers N` | Worker processes (default: auto `min(cpu_count, pages, 8)` capped by RAM at ~500 MiB/worker). |
| `--fast` | Skip heading-tier clustering and paragraph reflow while keeping reading order, tables, and warnings. |
| `--plain` | Omit `<!-- Page N -->` comments and `---` page separators. |
| `--ocr-fallback` / `--force-ocr` | Opt-in OCR on unreliable/wordless pages, or force whole-page OCR (mutually exclusive). |
| `--ocr-engine {tesseract,rapid}` | Select local OCR backend (default: `tesseract`; `--ocr-dpi` defaults to `300`). |
| `--check-ocr` | With no input paths, report the selected backend's availability as JSON; exit 0 if usable, 1 otherwise. |
| `--ocr-timeout SECONDS` | Set the positive per-page Tesseract recognition timeout (default: 60 seconds). |
| `--cache-dir DIR` / `--no-cache` | Override the cache directory or disable caching, even when the environment variable is set. |
| `--no-heuristics` | Disable heuristic corruption/wordless OCR routing while keeping deterministic font warnings. |
| `--images-output DIR` | Export embedded rasters (`>=30` units) and dense vector PNGs without emitting Markdown; pair with `--contact-sheet PATH`, or add `-o`, `--output-dir`, `-o -`, or `--json` to also emit a report. |
| `--render-pages DIR` | Render-only mode: write source-qualified full-page PNGs into `DIR` (`--dpi` defaults to `150`), print `Wrote <path>` unless `--quiet`, and exit without emitting Markdown. Conflicts with `--json`, `--metadata`, `--analyze`, `--list-images`, `--tables-output`, and `--check-ocr`; ignores `-o` and `--output-dir`. |
| `--tables-output DIR` | Export detected tables as collision-safe CSV files; add `-o`, `--output-dir`, `-o -`, or `--json` to also emit a report. |
| `--include-summary` | Prepend `<!-- extraction-summary: ... -->` as line 1 of the Markdown output. |
| `--analyze` / `--metadata` / `--list-images` | Print JSON routing verdict (`--analyze`), full metadata/font-risk assessment (`--metadata`), or embedded image inventory (`--list-images`) and exit. `--analyze` and `--list-images` honor `--pages`; `--metadata` inspects the full PDF. |

Supply one or more PDFs or directories. Directory inputs include direct PDF children in sorted order, including `.PDF`; `--recursive` includes nested PDFs. An empty directory selection fails before output is written. In a batch, a failed PDF rolls back the files it created and processing continues for the others. Aggregate JSON retains successful documents even when the batch exits with a failure, so check stderr and the exit status. Multi-PDF metadata, analysis, and image inventory return an ordered array of source/result objects.

Run `pypdftomd --help` (or `python -m pypdftomd --help`) for the full option list.

### Preflight and selective OCR

Run `--analyze` on unknown batches (optionally bounded with `--pages` on large PDFs) to inspect `verdict` (`text_based`, `needs_ocr`, or `mixed`), `page_count`, `assessed_pages`, `pages_needing_ocr`, `confidence`, `reasons`, `dense_vector_pages`, and `dense_image_pages` before paying OCR cost. Use `--metadata` to check `is_encrypted` and `needs_password` alongside font-risk details:

```sh
pypdftomd batch_doc.pdf --analyze
pypdftomd batch_doc.pdf --metadata
```

OCR replaces the page's embedded text, so native table and body structure on that page is lost. When recognition fails or times out, embedded text is retained with a warning. If the backend is unavailable, the output retains embedded text and reports `ocr_backend_unavailable`. A page that cannot be rendered gets `ocr_page_render_failed`; other pages continue. No recoverable text raises an error. When possible, an OCR fallback page image is saved in `--images-output`, or alongside the report written by `-o` or `--output-dir`, for visual inspection.

### Python API

```python
from pathlib import Path
from pypdftomd import ExtractionOptions, extract_text_from_pdf

markdown = extract_text_from_pdf(Path("report.pdf"))
options = ExtractionOptions(ocr_fallback=True, workers=2, include_summary=True)
markdown_with_ocr = extract_text_from_pdf(Path("report.pdf"), options=options)
```

Preflight inspection and structured table extraction share the same page analysis and bounding boxes:

```python
from pathlib import Path
from pypdftomd import extract_tables_with_bboxes, get_pdf_metadata

meta = get_pdf_metadata(Path("report.pdf"))
if not meta["needs_password"]:
    routing = meta["extraction_assessment"]["routing"]
    tables = extract_tables_with_bboxes(Path("report.pdf"), pages="1-3")
```

Pass either `options=ExtractionOptions(...)` or individual keyword arguments to `extract_text_from_pdf`; when `options` is provided, scalar keyword arguments are ignored.

<details>
<summary>Supported top-level Python API (<code>__all__</code>, 39 exports + <code>py.typed</code>)</summary>

- **Core extraction & types:** `extract_text_from_pdf` (alias `extract_pdf_text`), `ExtractionOptions`, `PageResult`, `DetectedTable`, `TableProvenance`.
- **`ExtractionOptions` fields:** `page_breaks=True`, `ocr_fallback=False`, `force_ocr=False`, `no_heuristics=False`, `pages=None`, `workers=None`, `ocr_dpi=300`, `ocr_timeout=60`, `ocr_engine="tesseract"`, `fast=False`, `include_summary=False`, `images_output=None`, `output_file=None`, `cache_dir=...` (pass `cache_dir=None` to disable caching).
- **Preflight & metadata:** `classify_pdf`, `get_pdf_metadata`.
- **Embedded & OCR extraction:** `extract_embedded_pages`, `extract_embedded_text`, `extract_ocr_pages`, `extract_ocr_text`, `extract_rapid_pages`, `probe_ocr_backend`, `OCR_DPI`, `OCR_PROVENANCE`.
- **Rendering & image export:** `render_page_images`, `extract_page_images`, `list_page_images`, `write_contact_sheets`, `intersection_area`.
- **Layout, fonts & tables:** `cluster_heading_tiers`, `discover_base_font_size`, `extract_document_font_stats`, `extract_tables_from_pdf`, `extract_tables_with_bboxes`, `table_quality_issues`, `to_markdown_table`, `write_extracted_tables`, `sanitize_cell`.
- **Diagnostics, warning constants & CLI:** `format_extraction_summary`, `summarize_page_warnings`, `TYPE3_FONT_WARNING`, `OCR_BACKEND_UNAVAILABLE_WARNING`, `OCR_TIMEOUT_WARNING`, `CHART_GRID_TABLE_WARNING`, `main`, `parse_args`, `__version__`.

</details>

### Caching

Result caching is opt-in and disabled by default when `PYPDFTOMD_CACHE_DIR` is unset (pass `cache_dir=None` to force-disable it). Enable it per call via `cache_dir`, on the CLI via `--cache-dir`, or process-wide via `PYPDFTOMD_CACHE_DIR`:

```sh
export PYPDFTOMD_CACHE_DIR=./.cache/pypdftomd
```

`--cache-dir` overrides the environment variable; `--no-cache` disables caching. Set the environment variable before the first process-wide cache use. Entries use the `pypdftomd-` prefix, are bounded to 128 entries, and key on document bytes, selected pages, extraction options, and backend versions. Requests that write side-effect files (`images_output` or `output_file`, including CLI `-o PATH`), actually run OCR fallback, or encounter degraded OCR or page/table extraction failures bypass the cache. Explicit `-o -` writes to stdout and remains cacheable. Cache errors and corrupt entries do not fail extraction.

## Limitations

- **Scanned PDFs and OCR structure:** Scanned or image-only pages require `--ocr-fallback` or `--force-ocr`. OCR operates on whole pages and loses native table and body structure on those pages.
- **Table detection gaps:** Table extraction is strongest on ruled and shaded grids. Borderless tables, tight sub-gutter spacing, filled callouts or parallel prose misread as grids, and contents or index pages remain known gaps; visually verify critical tables with `--render-pages`.
- **Charts and dense vector drawings:** Charts are not reconstructed into structured data (grids over chart marks emit `chart_grid_table`). Dense vector figures export as rendered PNGs only when `--images-output` is set. For slow, hung, or worker-crashing PDFs, see the [hung/slow PDF troubleshooting guide](https://github.com/MattBetancourt/pypdftomd/blob/main/docs/troubleshooting-hung-pdfs.md).
- **Non-HTTP(S) links:** Native HTTP(S) link annotations become Markdown links; internal PDF navigation links and other schemes keep readable labels without link targets.
- **Encrypted PDFs:** Password-protected PDFs must be decrypted before extraction (`--metadata` reports `is_encrypted` and `needs_password`).
- **Heuristic headings and reading order:** Headings and reading order remain heuristic.

## License

`AGPL-3.0-or-later`. See [LICENSE](https://github.com/MattBetancourt/pypdftomd/blob/main/LICENSE) and [THIRD_PARTY_NOTICES.md](https://github.com/MattBetancourt/pypdftomd/blob/main/THIRD_PARTY_NOTICES.md). `PyMuPDF` is used under its GNU AGPL-3.0 license rather than an Artifex commercial license, so `pypdftomd` retains `AGPL-3.0-or-later` copyleft obligations for distribution and network-service use (Section 13). [THIRD_PARTY_NOTICES.md](https://github.com/MattBetancourt/pypdftomd/blob/main/THIRD_PARTY_NOTICES.md) documents adapted upstream mechanisms (`liteparse`, `pdf-inspector`, `Docling`, and the `Adobe Glyph List`) and the licenses of the runtime dependency closure. Both license files are installed in the wheel metadata's `licenses` directory. The agent skill files in [skills/pypdftomd/](https://github.com/MattBetancourt/pypdftomd/blob/main/skills/pypdftomd/SKILL.md) are separately licensed under the [MIT License](https://github.com/MattBetancourt/pypdftomd/blob/main/skills/pypdftomd/LICENSE).
