Skip to content

Developing and Debugging BabelDOC

Language: English | 简体中文

BabelDOC is a PDF translation engine implemented as a Rust core extension (babeldoc._rust_il) hosted by Python orchestration and callback services. Primary development happens in a private repository and releases are synced to funstory-ai/BabelDOC. As a result, a public checkout contains the full engine source code and a lightweight smoke input (examples/ci/test.pdf), while there is no tests/ directory in the public tree.

If you want to report a bug or submit a patch upstream, see CONTRIBUTING.md. If you are working with a coding agent in this repository, see AGENTS.md.

Build BabelDOC from source on Linux, macOS, and Windows

Building from source compiles the 8-crate Rust workspace under rust/ into the Python abi3 extension babeldoc._rust_il via maturin==1.15.0 (targeting rust/py_bridge/Cargo.toml).

Prerequisites

  • Python: >=3.11,<3.15 on Linux, Windows, and Apple Silicon macOS. Intel macOS supports Python 3.11–3.13 because upstream onnxruntime does not provide Intel macOS wheels for Python 3.14.
  • uv: Install uv to manage the virtual environment and package builds.
  • Rust toolchain: Pin Rust 1.100.1 (the exact toolchain version used in CI).

Linux and macOS

rustup toolchain install 1.100.1 --profile minimal
rustup default 1.100.1

uv sync
uv run ruff check .
uv build
uv run babeldoc --help

Windows (MSVC)

On Windows, freetype-sys 0.23 compiles its bundled libpng against zlib.h using an include path that does not exist on disk. Fetch the Cargo dependencies first and point CFLAGS_x86_64_pc_windows_msvc at the libz-sys headers (matching the public wheel-build workflow) before running uv sync or uv build.

In Git Bash:

rustup toolchain install 1.100.1 --profile minimal
rustup default 1.100.1

cargo fetch --locked --manifest-path rust/py_bridge/Cargo.toml
cargo_home="$(cygpath -u "${CARGO_HOME:-$USERPROFILE/.cargo}")"
zlib_dir="$(ls -d "$cargo_home"/registry/src/*/libz-sys-*/src/zlib | head -n 1)"
export CFLAGS_x86_64_pc_windows_msvc="-I$(cygpath -w "$zlib_dir")"

uv sync
uv build
uv run babeldoc --help

Windows runtime note: If importing onnxruntime fails at runtime with DLL load failed, install the Microsoft Visual C++ Redistributable (vc_redist.x64.exe).

Runtime asset cache and incremental Rust builds

  • Asset cache path: BabelDOC downloads and caches layout ONNX models, embedded fonts, CMaps, tiktoken files, and default debug working directories under ~/.cache/babeldoc (lowercase babeldoc).
  • Pre-warming or restoring offline assets: Run uv run babeldoc --warmup once to download and verify all runtime assets. In air-gapped environments, generate a verified archive on a connected machine with babeldoc --generate-offline-assets <dir> and restore it with babeldoc --restore-offline-assets <zip-or-dir>.
  • Faster local Rust iteration: rust/Cargo.toml defines [profile.fastopt] (incremental release-style optimization with line tables) for faster local Cargo rebuilds.

Verify a change locally without an upstream test suite

A parser smoke run proves only that the binary builds and can parse and rewrite a PDF; it does not prove that layout detection, formula protection, translation, or target-language typesetting work correctly. Pick the verification level that matches the stage you changed.

1. Parser-and-writer smoke (no LLM API key)

This matches the public CI smoke check and exercises rust/parser_core into rust/writer_core:

uv run babeldoc \
  --openai \
  --openai-api-key dummy \
  --files examples/ci/test.pdf \
  --output ./smoke_out \
  --only-parse-generate-pdf \
  --skip-scanned-detection

Two caveats for this smoke command: - The CLI always validates --openai and --openai-api-key and initializes the default ONNX layout model (DocLayoutModel.load_onnx()) before entering do_translate(). A placeholder key avoids LLM calls, but a fresh machine without cached ~/.cache/babeldoc assets still needs network access (or restored offline assets) to load models and fonts. - --only-parse-generate-pdf jumps directly from Rust parsing to PDF writing. It skips scan detection, layout analysis, paragraph finding, formula classification, translation, and typesetting, so a green smoke run never validates changes in those later stages.

2. Single-page pipeline run without LLM calls (--pages and --skip-translation)

To exercise scan detection, layout detection, occluded-text filtering, paragraph finding, OCR classification, styles/formulas, typesetting, and PDF writing on a single page without calling an LLM:

uv run babeldoc \
  --openai \
  --openai-api-key dummy \
  --files input.pdf \
  --pages 5 \
  --skip-translation \
  --debug \
  --working-dir ./debug_work \
  --output ./out

Passing --skip-translation automatically sets auto_extract_glossary = False inside TranslationConfig, so no LLM requests are sent for glossary extraction or paragraph translation.

3. Full translation check on a real PDF

To verify translation orchestration, placeholder handling, or translated-text typesetting, run against a real OpenAI-compatible endpoint or inject a custom BaseTranslator subclass through the Python API (babeldoc.format.pdf.high_level.translate), then visually inspect the rendered output PDF on the affected pages.

Linux Python 3.14 script note: Python 3.14 on Linux defaults to forkserver for multiprocessing. In standalone Python scripts that call translate(), put the entry call inside if __name__ == "__main__": so worker subprocesses can import your script safely.

How BabelDOC splits work between Python and Rust

Python handles configuration, asset resolution, PyMuPDF pre/post-processing, multi-part splitting/merging, and external callbacks (ONNX layout, page rasterization, LLM HTTP requests, font subsetting). Rust owns the strongly typed intermediate representation (IR) and runs every core PDF parsing, analysis, translation-orchestration, typesetting, and content-stream writing stage inside babeldoc._rust_il.

flowchart TD
    IN["Input PDF"] --> PRE["Python: high_level.py\nPyMuPDF repair & preprocess"]
    PRE --> PARSE["Rust: parser_core\nParse PDF -> ParserIrDocument"]
    PARSE -->|--only-parse-generate-pdf| WRITER
    PARSE -->|normal pipeline| SCAN["Rust: ScanDetection\n(when ocr_mode=auto & !skip_scanned_detection)"]
    SCAN <-->|raster render| CB_SCAN["Python: ScanFileService"]
    SCAN --> LAYOUT["Rust: LayoutParser"]
    LAYOUT <-->|ONNX / RPC| CB_LAY["Python: LayoutService"]
    LAYOUT --> OCC["Rust: OccludedTextFilter"]
    OCC --> PARA["Rust: ParagraphFinder + OcrClassification"]
    PARA <-->|visibility check| CB_SCAN
    PARA --> SF["Rust: StylesAndFormulas"]
    SF -->|--skip-translation| TS
    SF -->|translate enabled| TR["Rust: TermExtraction + Translation\n(llm_only or ordinary)"]
    TR <-->|LLM HTTP + cache| CB_TR["Python: RustTranslatorService"]
    TR --> TS["Rust: Typesetting"]
    TS --> WRITER["Rust: writer_core\nBuild streams & embed fonts"]
    WRITER <-->|subset & bilingual merge| CB_WR["Python: WriterFileService / PdfAssembler"]
    WRITER --> POST["Python: fix_cmap, add_metadata,\nmigrate_toc, ResultMerger"]

Where the live code lives

  • rust/ir/schema.dsl.rs: Single-file schema DSL compiled by rust/ir_codegen into the typed per-stage IR (IrDocument, IrPage, Paragraph, CharacterPayload).
  • rust/parser_core/: PDF parsing and projection built on vendored rust/vendor/lopdf (fonts, CMaps, Type 0/Type 3 glyphs, graphics states, clips, curves, forms).
  • rust/pipeline_stages/: Core pipeline stages — src/stages/ (scan_detection.rs, occluded_text_filter.rs, invisible_text_filter.rs, ocr_classification.rs, paragraph_finder.rs, styles_and_formulas.rs, typesetting.rs), src/translation/ (ordinary.rs, llm_only.rs, paragraph_helpers.rs), and src/font_mapper.rs.
  • rust/writer_core/ and rust/font_core/: Rebuilt PDF content streams, font embedding, exact glyph widths, and write-time retry handling.
  • rust/py_bridge/: PyO3 extension (babeldoc._rust_il), stage runner (pipeline_runner.rs), Rust-to-Python log bridge (logging.rs), and callback scheduling.
  • babeldoc/format/pdf/high_level.py and translation_config.py: Entry points (translate, async_translate, do_translate), PyMuPDF input repair, multi-part splitting (split_manager.py), and merging (result_merger.py).
  • babeldoc/rust_*_service.py, babeldoc/docvision/, babeldoc/translator/, and babeldoc/format/pdf/document_il/backend/pdf_assembler.py: Python callback services invoked by Rust for layout detection, scan/OCR rendering, LLM calls, font subsetting, and bilingual assembly.

Do not get misled by auxiliary Python modules: babeldoc/format/pdf/document_il/utils/fontmap.py, formular_helper.py, and babeldoc/rust_debug_service.py remain only for auxiliary tools (rpc_doclayout*, italic_*, or rust_parser_service.py helpers). Mainline font mapping, formula classification, typesetting, and --debug stage JSON serialization all execute in Rust.

Inspect intermediate stages and trace common PDF symptoms

Dump intermediate IR locally

  • --debug --working-dir <dir>: Keeps <dir>/<input_stem>/ after execution (without --working-dir, --debug writes to ~/.cache/babeldoc/working/<input_stem>/ and does not auto-clean it). Produces input.decompressed.pdf, layout bounding-box previews (ocr-box-image/<page>.jpg), *.decompressed.pdf, and pretty-printed stage JSON files written by Rust: create_il.debug.json, layout_generator.json, paragraph_finder.json, styles_and_formulas.json, il_translated.json, add_debug_information.json, and typsetting.json (note the literal filename without the first e), plus conditional artifacts such as detect_scanned_file.json (when scan detection runs) and debug_original.pdf (when a bilingual dual PDF is generated). --only-parse-generate-pdf skips middle-stage JSON dumps.
  • --capture-stages --capture-dir <dir>: Compiled in by default in standard wheels. Writes zstd-compressed stage JSON snapshots (parser, scan, layout, paragraph, styles, translation, typesetting) to <dir>/<doc_stem>/part-0000/<stage>.json.zst. Decompress locally with system zstd -d (or a separately installed Python zstandard package, because pyzstd is not a default dependency). Keep stage-capture dumps local and do not upload multi-gigabyte archives to GitHub issues.

Reading dumps under --skip-translation: When --debug or --capture-stages is active together with --skip-translation, BabelDOC still runs a passthrough conversion (skip_translation_to_translation) and writes il_translated.json or translation.json.zst so downstream stages stay uniform. The presence of that file alone does not prove that an LLM translated the page.

Map a visible symptom to the right stage

  • Missing characters or garbled copy-paste text: Start at create_il.debug.json (or parser.json.zst). If characters are already missing or decoded as (cid:...), inspect rust/parser_core/ (font backends, CMaps, Type 0 descendant fallback, Type 3 glyphs). If source text is intact there, inspect paragraph_finder.json and styles_and_formulas.json; diffing layout against paragraph spans occluded_text_filter (rust/pipeline_stages/src/stages/occluded_text_filter.rs and rust/py_bridge/src/occluded_text_filter.rs), paragraph_finder.rs, and ocr_classification.rs (InvisibleMetadataSkip). If translated text exists in il_translated.json but disappears or copies wrong in the final PDF, inspect typsetting.json (font_mapper.rs and typesetting.rs), rust/writer_core/, and pdf_assembler.py (font subsetting and fix_cmap).
  • Formulas or inline math translated or broken: Check layout_generator.json and ocr-box-image/ to see whether the layout model labeled the region as isolate_formula or body text. Next check styles_and_formulas.json (styles_and_formulas.rs, shared/formula_helper.rs, shared/formula_patterns.rs). If formulas were preserved as placeholders in styles_and_formulas.json yet broke after translation, inspect rust/pipeline_stages/src/translation/.
  • Paragraph stays in the original language: BabelDOC explicitly records whole-paragraph passthrough in ParagraphTranslationOutcome::Passthrough { reason } (non-DocumentText origin, single-formula or pure-numeric blocks, vertical text, text with more than 80% undecoded CID characters, text shorter than min_text_length (default 5), ParagraphOcrState::InvisibleMetadataSkip, or an LLM reply that is empty or unchanged after normalization), and typesetting also falls back to original layout on ExhaustedNoFit when translated text cannot fit in the layout box. Separately, within a translated paragraph, individual untranslated units (such as inline formulas or preserved source spans with unicode = None) replay their original glyphs without forcing the whole paragraph back to source.
  • Scanned PDFs and ocr_mode: BabelDOC uses a unified tri-state ocr_mode ("auto", "on", "off"), defaulting to "auto". When ocr_mode is omitted, legacy flags resolve in precedence order: ocr_workaround -> "on", auto_enable_ocr_workaround -> "auto", skip_scanned_detection -> "off". In "auto", front-gate scan detection raises ScannedPDFError when pure-scan pages reach at least 80% of selected pages (page_indices.len(), stopping page checks early once the outcome is already determined), and paragraph-level ocr_classification tags each paragraph as VisibleVector, BackgroundOcr (masking scanned background behind translated text, with optional adaptive_ocr_mask), or InvisibleMetadataSkip. "on" forces OCR masking, skips scan rejection, and disables rich-text translation; "off" skips scan rejection and disables OCR masking.

Design constraints and interface boundaries to know before editing

  • Original replay and translated typesetting coexist on the same line: Untranslated elements (formulas, symbols, passthrough spans) need to replay original PDF drawing facts, while translated text must re-wrap, scale, and avoid surrounding graphics in the target language. Improving original visual roundtrip fidelity is not automatically the same as making a translated page readable, and dropping problematic text in the parser can silently break translation or OCR layers downstream.
  • Engine role vs SDK compatibility: BabelDOC is an internal PDF translation engine built to be embedded in higher-level applications such as PDFMathTranslate-next and service wrappers. To keep pdf2zh_next maintenance overhead low, top-level entry points (high_level.translate, high_level.async_translate, TranslationConfig, TranslateResult, WatermarkOutputMode, and Glossary) are kept relatively stable in practice, though this is not a compatibility guarantee — and BabelDOC does not promise a stable external SDK across internal IR or helper modules.
  • Maintainer-only surfaces: The bundled babeldoc CLI, the built-in openai(-compatible) connector, and the rpc_doclayout* layout backends are maintainer debugging and testing tools. They carry no compatibility guarantees and do not accept community feature requests or PRs.
  • Release history: Recent architecture transitions, compatibility notes, and community contributions are documented in docs/release-notes/.