Skip to main content
Glama
pdf-layout-mcp

pdf-layout-mcp

by Sweet-F1G
README.md
# `vector-pdf-translator-mcp` — Open-Core AI Add-On for Layout-Preserving PDF Translation

> **Local MCP server, HTTP/OpenAPI bridge, and CLI** allowing AI agents (**Claude Desktop, Antigravity, Cursor, Gemini CLI, ChatGPT, Open WebUI**) to translate complex vector PDFs while preserving schematics, table borders, brand banners, and typography.

---

## Why Naive PDF Translators Fail (Engineering Challenges Solved)

Standard PDF translation pipelines either convert pages into blurry raster images or reflow text blindly, breaking multi-column technical tables and engineering drawings. This project solves five core failure modes:

1. **Vector & Image Preservation During Redaction**: Source text is excised strictly with `PDF_REDACT_IMAGE_NONE` and `PDF_REDACT_LINE_ART_NONE` so background gradients, CAD schematics, and table grids remain 100% vector-exact.
2. **Target Alphabet Glyph Verification (Zero Tofu)**: Pre-validates every required Unicode code point against the target TrueType/OpenType font (`fitz.Font.has_glyph`) before rendering (e.g., Mongolian `ӨөҮү`, Kazakh `ӘәҒғҚқҢңӨөҰұҮүҺһІі`, Uzbek `OʻoʻGʻgʻ`).
3. **Typography Auto-Shrink & Color Fidelity**: Translated technical prose frequently expands by 15–35%. A step-down fitting loop (`0.5 pt` steps down to `4.5 pt`) fits text into original `bbox` boundaries while retaining original RGB colors (e.g. white text on dark headers) and bold/regular weights, preserving original text rotation (`0°`, `90°`, `180°`, `270°`).
4. **RTL (Arabic Dialects & Hebrew) + Selective Layout Mirroring**: Renders Arabic/Hebrew via MuPDF HarfBuzz (`insert_htmlbox` with `<p dir="rtl">`) to guarantee proper contextual letter shaping and BiDi ordering of embedded numbers/codes (`1000 V`, `ISO 9001`), supports **Arabic dialect selection** (`msa`, `egyptian`, `gulf`, `levantine`, `maghrebi`), and performs **selective horizontal mirroring** (`mirror_layout="auto"`): table columns, headers, and axis-aligned dividers mirror Right-to-Left while vector diagrams/schematics, raster images, and arrow callouts stay anchored in place.
5. **Audit & Surgical Patching Loop**: Multi-pass line audit compares original vs. translated PDFs (normalizing PyMuPDF non-breaking spaces `\xa0`) and allows surgical coordinate patching (`pdf_patch_regions`) without re-laying out approved pages.

---

## Open-Core Architecture (Public Core vs. Private Extensions)

This repository implements the **Open-Core** foundation (complete MCP/OpenAPI server, CLI, baseline vector engine, and synthetic test suite). Advanced enterprise heuristics are isolated behind formal extension protocols in [`src/pdf_layout_mcp/core/plugins.py`](src/pdf_layout_mcp/core/plugins.py) and loaded dynamically via `PDF_LAYOUT_PLUGIN_MODULE`.

| Capability | Public Open-Core (This Repo) | Private Production Extensions *(Not Included)* |
|---|---|---|
| **Agent Protocols** | Full MCP JSON-RPC 2.0 (`stdio`) + HTTP/OpenAPI 3.1.0 bridge + CLI | Multi-tenant queue & worker orchestration |
| **PDF Vector Engine** | In-place PyMuPDF redaction, auto-shrink, RTL BiDi + selective table mirroring, surgical `bbox` patcher | Multi-row complex table parser, semantic CAD arrow re-anchoring |
| **Scanned / Raster PDFs** | Vector text layer required | Hybrid PaddleOCR / VLM extraction + background inpainting |
| **Translation & TM** | LLM adapter (Gemini / OpenAI / OpenRouter / Ollama) + Arabic dialect selector (`msa`/`egyptian`/`gulf`/`levantine`/`maghrebi`) + JSON cache | Domain Translation Memory (TM) + fuzzy matching + industrial glossaries |
| **Quality Assurance** | Text-diff residual auditor + PNG preview exporter | Automated multimodal VLM collision/overflow detector (`VisualQAPlugin`) |

```mermaid
flowchart LR
    Agent["AI App<br/>(Claude / Antigravity / Cursor / ChatGPT)"] -->|MCP stdio or OpenAPI| Server["pdf-layout-mcp<br/>(8 Tools)"]
    Server --> Core["Open-Core Engine<br/>(Extract / Redact / Auto-Shrink / Audit)"]
    Core -.->|"PDF_LAYOUT_PLUGIN_MODULE<br/>(Optional Private Pro Plugins)"| Pro["LayoutPlugin / VisualQAPlugin<br/>(Table Splitter, OCR, VLM QA, Domain TM)"]
    Core --> Output["Translated Vector PDF"]
```

---

## Production Case Study (Anonymized)

The architecture behind this engine was battle-tested in production to localize a **55-page industrial electrical cable catalog** (tables, technical specifications, standards, stepped marking diagrams, and vector cross-sections) from **Russian to Mongolian Cyrillic**:
- **Protected Domain Integrity**: Model codes, standard identifiers (`GOST`, `IEC`, `ISO`), electrical formulas, and dimensional tolerances stayed untouched.
- **Zero Layout Corruption**: Vector schematics and multi-column spec tables preserved intact; residual lines caught via audit and patched surgically.
- **Business Impact**: Accelerated localization from weeks of manual DTP layout work to hours, directly enabling the initiation of an official cross-border B2G/enterprise trade deal.

*(Proprietary customer files, industry glossaries, and specialized layout heuristics are intentionally excluded from this public repository.)*

---

## Quickstart

### 1. Local Setup

```bash
python3 -m venv .venv
.venv/bin/pip install --upgrade setuptools wheel
.venv/bin/pip install -e ".[dev]"
cp .env.example .env
```

> **Note on Fonts**: No proprietary font binaries are shipped in this repo. On macOS/Linux, system Unicode fonts (`Arial`, `DejaVu Sans`, `Liberation Sans`, `Noto Sans`) are auto-discovered. For extended scripts, drop open-source **Noto Sans** (SIL OFL) fonts into `src/pdf_layout_mcp/fonts/` or pass `--font-regular`.

### 2. Connect to Any AI Client

- **MCP Clients (Claude Desktop, Antigravity, Cursor, Gemini CLI)**:  
  Run `.venv/bin/pdf-layout-mcp configs` to generate a ready-to-paste `mcpServers` block with your exact local Python path (or adapt [`integrations/mcp_config.json`](integrations/mcp_config.json)).
- **HTTP / OpenAPI Agents (ChatGPT Custom Actions, Open WebUI, REST)**:  
  ```bash
  .venv/bin/pdf-layout-mcp serve-http --port 8765
  ```
  Schema served at `http://127.0.0.1:8765/openapi.json` (also exported in [`integrations/openapi_schema.json`](integrations/openapi_schema.json)).

### 3. Run Verification Tests

```bash
.venv/bin/pytest tests -v
```

---

## License

Released under **AGPL-3.0-or-later**. Any network/SaaS deployment incorporating this codebase must disclose its modified source under AGPL-3.0, while private/enterprise extensions can be licensed separately.