Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 7 min read

What we learned building PDF Craft (6,800+ GitHub stars): scanned books to Markdown, EPUB, and translated PDFs

Over the past year, PDF Craft, our MIT-licensed Python library for scanned books and papers, has grown to 6,800+ stars on GitHub. Most developers and researchers find it after hitting the same wall: scanned PDFs are fine

What we learned building PDF Craft (6,800+ GitHub stars): scanned books to Markdown, EPUB, and translated PDFs

Over the past year, PDF Craft, our MIT-licensed Python library for scanned books and papers, has grown to 6,800+ stars on GitHub. Most developers and researchers find it after hitting the same wall: scanned PDFs are fine if you just want to read page 12 on a 27-inch monitor, and painful the moment you want to read a 300-page book on a phone or e-reader, pull clean Markdown from a two-column paper with equations, or translate a textbook without shredding its figures and footnotes.

Plain OCR tools handle single pages well enough, then fall apart on whole books. Headers and page numbers bleed into body paragraphs, multi-column sentences get glued together out of order, footnotes disappear into the middle of the next paragraph, and if you later decide you want an EPUB or a translation after already generating Markdown, you end up paying to run OCR all over again.

Alongside the open-source Python library, we also run a hosted web version at pdfcraft.ai for people who do not want to set up Poppler, CUDA, or OCR keys. Here is a look at what it actually outputs, a few architectural decisions that saved us a lot of headaches, and where the rough edges still are.

What the output looks like in practice

Before getting into internals, here are two real conversions rather than synthetic demos.

First, a paper everyone in ML recognizes (Attention Is All You Need) converted and rendered in our Conversion Examples library, with the extracted table of contents on the left, equations and diagrams preserved in the reading flow, and each paragraph linked back to its bounding box on the original PDF page:

Attention Is All You Need converted in PDF Craft with extracted TOC, equations, Figure 2, and highlighted source bounding box on the original PDF

Second, a scanned math page from The Works of Archimedes going from a fixed-layout English scan (with a geometric diagram, display formulas, and a footnote) to a reflowable translated page:

Scanned page from The Works of Archimedes on the left and reflowed translated page with diagram, equations, and footnote on the right

Depending on what you need, PDF Craft can output:

  • Editable Markdown with cropped image assets
  • Reflowable EPUB with chapters, TOC, footnotes, and book metadata
  • Translated or bilingual EPUB (either from a scanned PDF or from an existing EPUB)
  • Translated PDF written back onto the original page canvas while keeping figures and annotations

Why we stopped going straight from OCR to Markdown

Early on, going directly from OCR to Markdown or EPUB looked simpler. The problem is that Markdown and EPUB are presentation formats: once you write them out, you throw away page dimensions, pixel bounding boxes (bbox), and original reading-order coordinates.

If you want to switch from translated-only to bilingual later, add a second language, or write a translation back onto the original PDF canvas, you have to re-run OCR from scratch.

So we put an intermediate ZIP archive called .pcex between the OCR stage and every renderer or translator:

Diagram of PDF Craft's .pcex archive turning one OCR pass into Markdown, reflowable EPUB, bilingual EPUB, and translated PDF

Inside a .pcex archive, the layout is intentionally boring and inspectable:

book.pcex
β”œβ”€β”€ manifest.json       # format version, producer, book metadata
β”œβ”€β”€ pages.xml           # page pixel dimensions, DPI, coordinate space
β”œβ”€β”€ chapters/           # logical reading flow + footnotes + source bbox maps
β”œβ”€β”€ assets/             # content-hashed cropped images, tables, formulas
β”œβ”€β”€ toc.xml             # hierarchical table of contents
β”œβ”€β”€ furnitures.xml      # headers, footers, page numbers
└── translations/       # stackable translation layers isolated by ID

A logical paragraph stays one TextFlowItem even when an illustration or column break splits it across multiple bounding boxes. Markdown and EPUB renderers walk the logical flow; the PDF writeback renderer uses the stored page_index and bbox coordinates to refill the original pages. Translations live as separate layers under translations/, so the original extraction is never overwritten.

A few engineering tradeoffs that mattered

1. Streaming books without waiting for page 200

Nobody wants to stare at a spinner for 15 minutes on a long scan. Streaming OCR page by page sounds easy until you remember two things: concurrent OCR workers finish out of order, and paragraphs and footnotes routinely cross page breaks.

We ended up using a fixed three-page primary window for footnote screening and optional LLM refinement, with one strict rule: a page's refinement prompt sees only its own score plus immutable primary snapshots of its immediate neighbors, never the neighbor's refined output. Waiting for earlier pages to finish refining would serialize the whole book again and make prompts depend on network timing. Giving up cross-page score sharing bought us parallel scheduling, deterministic caching, and a bounded reorder queue that emits closed paragraphs through on_body and on_footnote callbacks as pages complete.

2. Keeping LLMs from breaking EPUB XML and math

If you have ever written a quick script to translate an EPUB with an LLM, you already know the failure modes: dropped closing tags, broken footnote IDs, or the model helpfully rewriting 16 \times into prose. And if you validate too strictly on raw strings, you burn retry tokens because the model added a trailing space.

In PDF Craft, prose translation and XML structure filling are split into two stages. Context around group boundaries helps keep pronouns and references coherent, and then deterministic validation checks node IDs, required tags, and text alignment. Unambiguous whitespace differences get recovered deterministically with zero retries; only genuinely missing content or ambiguous tag-boundary placement triggers a bounded retry.

For inline equations, we keep them visible in the chapter XML so the translator understands the math in context, avoid brittle LaTeX diffing during structure validation, and restore the exact original source formula deterministically after validation passes.

3. Writing translations back onto scanned PDFs (and its real limits)

Translating a PDF in place is tricky because translated text almost never matches the original length. Painting text inside each individual OCR box leads to mismatched font sizes across neighboring paragraphs and cramped headings.

Our PDF writeback path builds four layers: a font-free visual base via Ghostscript (so original text is no longer selectable underneath), a local background erasure mask sampled from each box's median background color, translated text and vector math laid out with Qt QTextLayout, and the source PDF's original /Annots mounted back on top. Layout runs in two stages: first flowing each logical paragraph continuously across columns and page breaks around protected figures, then normalizing body font scale per page with a minimum heading size ratio.

The honest caveat: erasure uses solid color-matched rectangles, not generative inpainting. On clean or off-white paper it blends well; when text sits on top of heavy texture, gradients, or dense table gridlines, you will see a flat patch. Text baked inside bitmap illustrations is also left alone rather than erased. For text-heavy books read on phones or Kindle, EPUB is still the better output; translated PDF is mostly for papers and technical manuals where figure-to-text spatial alignment matters.

Running it in Python (local GPU or remote OCR)

The library requires Python 3.11 to 3.13 and Poppler on your system. You can point it at a remote OCR endpoint (no local GPU needed) or run locally on CUDA. Supported OCR backends include DeepSeek OCR, DeepSeek OCR 2, Unlimited OCR, and MiniCPM-OCR.

python -m pip install pdf-craft

Basic conversion to Markdown (saving a reusable .pcex archive along the way):

from pdf_craft import DeepSeekOCRVendorConfig, PDFCraft, PDFOptions

craft = PDFCraft(
    pdf=PDFOptions(
        ocr=DeepSeekOCRVendorConfig(
            base_url="https://example.com/v1",
            api_key="your-api-key",
            model="deepseek-ocr",
        ),
    ),
)

craft.convert_pdf_to_markdown(
    "input.pdf",
    "output.md",
    extraction_path="book.pcex",
)

For EPUB, swap the last call to craft.convert_pdf_to_epub("input.pdf", "output.epub"). If you are inside an async app, use AsyncPDFCraft with the same options.

If you have an NVIDIA GPU and want OCR completely offline on your own machine:

python -m pip install "pdf-craft[local]"

(Macs and CPU-only machines should stick to remote OCR or the hosted service since local mode requires CUDA. Translated PDF writeback also requires Ghostscript, local fonts, and optionally Matplotlib + TeX if you want inline equations rendered as vector graphics instead of plain-text fallback.)

Hosted web app, REST API, and MCP

If you do not want to install Poppler, Ghostscript, or manage OCR credentials just to test a book, there is a hosted web workspace at pdfcraft.ai (pay-as-you-go per page, no subscription, with $1 in trial credits on new accounts).

For scripting or agent workflows, there is also a hosted REST API and a remote MCP server over Streamable HTTP at https://api.pdfcraft.ai/v1/mcp (supporting OAuth 2.1 or Bearer API keys, documented in the MCP setup guide). That lets an AI agent check balance, estimate cost upfront, upload file bytes, and pull back finished Markdown or EPUB instead of choking on a raw scanned PDF attachment.

Open-source ecosystem

Everything in the core pipeline is open source under oomol-lab:

  • oomol-lab/pdf-craft (MIT): scanned PDF extraction, .pcex, Markdown/EPUB export, and PDF translation writeback
  • oomol-lab/epub-translator (MIT): dedicated EPUB whole-book and bilingual translation
  • oomol-lab/wiki-graph (Apache 2.0): turns converted EPUB or Markdown books into structured summaries, chapter topology, and knowledge graphs

If you want to judge output quality before installing anything, browse a few papers and books side by side against their original scans in the Conversion Examples library. And if you run into a stubborn layout, footnote edge case, or OCR quirk on your own PDFs, issues and PRs on GitHub are very welcome.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.