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.15on Linux, Windows, and Apple Silicon macOS. Intel macOS supports Python 3.11–3.13 because upstreamonnxruntimedoes 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
onnxruntimefails at runtime withDLL 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(lowercasebabeldoc). - Pre-warming or restoring offline assets: Run
uv run babeldoc --warmuponce to download and verify all runtime assets. In air-gapped environments, generate a verified archive on a connected machine withbabeldoc --generate-offline-assets <dir>and restore it withbabeldoc --restore-offline-assets <zip-or-dir>. - Faster local Rust iteration:
rust/Cargo.tomldefines[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
--openaiand--openai-api-keyand initializes the default ONNX layout model (DocLayoutModel.load_onnx()) before enteringdo_translate(). A placeholder key avoids LLM calls, but a fresh machine without cached~/.cache/babeldocassets still needs network access (or restored offline assets) to load models and fonts. ---only-parse-generate-pdfjumps 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
forkserverfor multiprocessing. In standalone Python scripts that calltranslate(), put the entry call insideif __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 byrust/ir_codegeninto the typed per-stage IR (IrDocument,IrPage,Paragraph,CharacterPayload).rust/parser_core/: PDF parsing and projection built on vendoredrust/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), andsrc/font_mapper.rs.rust/writer_core/andrust/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.pyandtranslation_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/, andbabeldoc/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, andbabeldoc/rust_debug_service.pyremain only for auxiliary tools (rpc_doclayout*,italic_*, orrust_parser_service.pyhelpers). Mainline font mapping, formula classification, typesetting, and--debugstage 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,--debugwrites to~/.cache/babeldoc/working/<input_stem>/and does not auto-clean it). Producesinput.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, andtypsetting.json(note the literal filename without the firste), plus conditional artifacts such asdetect_scanned_file.json(when scan detection runs) anddebug_original.pdf(when a bilingualdualPDF is generated).--only-parse-generate-pdfskips 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 systemzstd -d(or a separately installed Pythonzstandardpackage, becausepyzstdis 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--debugor--capture-stagesis active together with--skip-translation, BabelDOC still runs a passthrough conversion (skip_translation_to_translation) and writesil_translated.jsonortranslation.json.zstso 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(orparser.json.zst). If characters are already missing or decoded as(cid:...), inspectrust/parser_core/(font backends, CMaps, Type 0 descendant fallback, Type 3 glyphs). If source text is intact there, inspectparagraph_finder.jsonandstyles_and_formulas.json; diffinglayoutagainstparagraphspansoccluded_text_filter(rust/pipeline_stages/src/stages/occluded_text_filter.rsandrust/py_bridge/src/occluded_text_filter.rs),paragraph_finder.rs, andocr_classification.rs(InvisibleMetadataSkip). If translated text exists inil_translated.jsonbut disappears or copies wrong in the final PDF, inspecttypsetting.json(font_mapper.rsandtypesetting.rs),rust/writer_core/, andpdf_assembler.py(font subsetting andfix_cmap). - Formulas or inline math translated or broken: Check
layout_generator.jsonandocr-box-image/to see whether the layout model labeled the region asisolate_formulaor body text. Next checkstyles_and_formulas.json(styles_and_formulas.rs,shared/formula_helper.rs,shared/formula_patterns.rs). If formulas were preserved as placeholders instyles_and_formulas.jsonyet broke after translation, inspectrust/pipeline_stages/src/translation/. - Paragraph stays in the original language: BabelDOC explicitly records whole-paragraph passthrough in
ParagraphTranslationOutcome::Passthrough { reason }(non-DocumentTextorigin, single-formula or pure-numeric blocks, vertical text, text with more than 80% undecoded CID characters, text shorter thanmin_text_length(default5),ParagraphOcrState::InvisibleMetadataSkip, or an LLM reply that is empty or unchanged after normalization), and typesetting also falls back to original layout onExhaustedNoFitwhen translated text cannot fit in the layout box. Separately, within a translated paragraph, individual untranslated units (such as inline formulas or preserved source spans withunicode = None) replay their original glyphs without forcing the whole paragraph back to source. - Scanned PDFs and
ocr_mode: BabelDOC uses a unified tri-stateocr_mode("auto","on","off"), defaulting to"auto". Whenocr_modeis 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 raisesScannedPDFErrorwhen 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-levelocr_classificationtags each paragraph asVisibleVector,BackgroundOcr(masking scanned background behind translated text, with optionaladaptive_ocr_mask), orInvisibleMetadataSkip."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-nextand service wrappers. To keeppdf2zh_nextmaintenance overhead low, top-level entry points (high_level.translate,high_level.async_translate,TranslationConfig,TranslateResult,WatermarkOutputMode, andGlossary) 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
babeldocCLI, the built-inopenai(-compatible) connector, and therpc_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/.