Skip to main content
Glama
PDF Extractor Pro
by narc-kany
README.md
<div align="center">

# PDF Extractor Pro Skill

**An AI Agent Skill & MCP Server for Mathematically Verified, Lossless `PDF → Markdown + Analytical JSON`**

[![Agent Skill](https://img.shields.io/badge/Agent_Skill-Claude_%7C_Claude_Code_%7C_Codex_%7C_Cursor-7c3aed?style=for-the-badge)](Skill.md)
[![MCP Federated](https://img.shields.io/badge/MCP-SharePoint_%7C_Drive_%7C_S3_%7C_Qdrant_%7C_Neo4j-0f172a?style=for-the-badge)](#mcp-federation--ocr-configuration)
[![YouTube Demo](https://img.shields.io/badge/YouTube-10s_Demo-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://youtube.com/shorts/d_22M17a2X8)

[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/license-MIT-10b981)](LICENSE)
[![Token Conservation](https://img.shields.io/badge/Token_Conservation_%CE%B7-%E2%89%A5_0.998-06b6d4)](#measured-extraction-quality)
[![KL Divergence](https://img.shields.io/badge/D__KL-%3C_1e--4-2563eb)](#mathematical--engineering-guarantees)
[![Release](https://img.shields.io/badge/release-v2.1_Enterprise-f59e0b)](#)

<p>
  <strong>Owner & Architect:</strong> Sivanesh S (<code>dodi / narc-kany</code>)
</p>

<p>
  <a href="#use-as-an-ai-agent-skill">Use with Claude & LLMs</a> •
  <a href="#measured-extraction-quality">Benchmarks</a> •
  <a href="#architecture--mcp-federation">Architecture</a> •
  <a href="#quick-start-cli">CLI Quick Start</a> •
  <a href="Skill.md">Full Spec (Skill.md)</a>
</p>

</div>

---

> **Why this skill exists:** Standard PDF parsers silently drop table cells, scramble multi-column layouts, and hallucinate blurry numbers—poisoning RAG pipelines and compliance archives before your LLM ever sees a prompt. **PDF Extractor Pro** gives AI agents (**Claude, Claude Code, OpenAI Codex, Cursor, Gemini, and MCP clients**) a deterministic, mathematically verified document ingestion engine where **quality is *measured*, never asserted.**

---

## Watch the 10-Second Overview

<div align="center">

[![Stop Letting Bad PDF Parsers Wreck Your RAG Pipeline](https://img.youtube.com/vi/d_22M17a2X8/hqdefault.jpg)](https://youtube.com/shorts/d_22M17a2X8)

**[Watch on YouTube Shorts](https://youtube.com/shorts/d_22M17a2X8)** • **[Standard YouTube Link](http://www.youtube.com/watch?v=d_22M17a2X8)** — featured on the **dodi** channel

</div>

---

## Use as an AI Agent Skill

`pdf_extractor_pro_skill` ships with a formal [`Skill.md`](Skill.md) specification, deterministic Python execution modules, and a native **Model Context Protocol (MCP)** server so LLMs can invoke verified bulk extraction directly inside agentic workflows.

| Platform / Runtime | How to Load This Skill |
| :--- | :--- |
| **Claude Code** | Clone or copy this repository into `.claude/skills/pdf-extractor-pro/` (project-scoped) or `~/.claude/skills/pdf-extractor-pro/` (global). Claude Code automatically discovers `Skill.md` and triggers it on PDF extraction, verification, or RAG ingestion tasks. |
| **Claude Desktop / Claude.ai** | Upload the skill folder (`Skill.md` + supporting `reference/`, `features/`, `scripts/`, `tools/`) in Claude Skills, or register the MCP server in `claude_desktop_config.json` (see [`reference/mcp_integration.md`](reference/mcp_integration.md)). |
| **OpenAI Codex / Cursor / Windsurf / Cline** | Add the repo to your workspace skills directory (e.g., `.codex/skills/` or `.cursor/rules/`) pointing to [`Skill.md`](Skill.md), and attach the MCP server from `tools/` for remote SharePoint, Drive, S3, Qdrant, and Neo4j operations. |
| **Any MCP-Compatible Agent** | Run the MCP server entrypoint inside `tools/` with the connector environment variables listed in [`reference/mcp_integration.md`](reference/mcp_integration.md). |

### Example Prompts Once Loaded

```text
"Use pdf_extractor_pro_skill to convert all PDFs in ./contracts into lossless Markdown + JSON and verify η ≥ 0.998."
```

```text
"Ingest Q4 financial statements from s3://corp-filings/q4/ using PDF Extractor Pro, quarantine any Tier-4 OCR regions, and sync verified chunks to Qdrant and Neo4j."
```

```text
"Run the cryptographic SHA-256 cross-link check and red-team evaluation suite on ./pdfx_out and summarize any audit flags."
```

---

## Measured Extraction Quality

<div align="center">
  <img src="./docs/assets/benchmark_chart.png" alt="PDF Extractor Pro v2.1 Measured Extraction Quality vs Legacy PDF Parsers" width="100%" />
</div>

### Side-by-Side Metric Breakdown

| Metric | Legacy Parsers | PDF Extractor Pro (Verified) | Improvement | Enforced Gate |
| :--- | :---: | :---: | :---: | :--- |
| **Token Conservation (`η`)** | `86.5%` | **`99.8%`** `██████████` | **`+13.3%`** | Mandatory SLA `η ≥ 0.998` |
| **Table Cell Recall** | `74.0%` | **`99.4%`** `██████████` | **`+25.4%`** | Full cell, span & row preservation |
| **Multi-Column Reading Order** | `68.0%` | **`100.0%`** `██████████` | **`+32.0%`** | Strict-DAG 2D Kahn's topological sort |
| **Audit & Lineage Traceability** | `20.0%` | **`100.0%`** `██████████` | **`+80.0%`** | UUIDv5 + mutual SHA-256 + Merkle proofs |
| **Distributional Fidelity** | Unmeasured | **`Verified`** | **Lossless** | Unigram & Bigram `D_KL < 1e-4` |

```mermaid
%%{init: {'theme': 'base', 'themeVariables': { 'xyChart': { 'backgroundColor': '#0d1117', 'titleColor': '#f0f6fc', 'xAxisLabelColor': '#c9d1d9', 'yAxisLabelColor': '#c9d1d9', 'xAxisTitleColor': '#8b949e', 'yAxisTitleColor': '#8b949e', 'plotColorPalette': '#484f58, #06b6d4' }}}}%%
xychart-beta
    title "Legacy PDF Parsers (Gray) vs. PDF Extractor Pro Verified (Cyan) — %"
    x-axis ["Token Conservation (η)", "Table Cell Recall", "Multi-Column Order", "Audit & Lineage"]
    y-axis "Accuracy / Compliance (%)" 0 --> 105
    bar [86.5, 74.0, 68.0, 20.0]
    bar [99.8, 99.4, 100.0, 100.0]
```

---

## Architecture & MCP Federation

<div align="center">
  <img src="./docs/assets/architecture_flow.png" alt="PDF Extractor Pro Agent Skill and Bijective MCP Federation Architecture" width="100%" />
</div>

### Live Pipeline Flow (Native GitHub Diagram)

```mermaid
flowchart TB
    classDef agent fill:#2e1065,stroke:#a855f7,color:#f5f3ff,stroke-width:2px
    classDef source fill:#0c4a6e,stroke:#38bdf8,color:#f0f9ff,stroke-width:2px
    classDef gate fill:#0f172a,stroke:#06b6d4,color:#ecfeff,stroke-width:2px
    classDef artifact fill:#064e3b,stroke:#10b981,color:#ecfdf5,stroke-width:2px
    classDef sink fill:#1e293b,stroke:#94a3b8,color:#f8fafc,stroke-width:2px

    subgraph T1["1. AI Agent & Skill Layer"]
        direction LR
        AG1["Claude / Claude Code"]:::agent
        AG2["OpenAI Codex"]:::agent
        AG3["Cursor / IDE Agents"]:::agent
        AG4["Skill.md + MCP Server"]:::agent
    end

    subgraph T2["2. Cloud & Local Ingestion (MCP Federation)"]
        direction LR
        S1["SharePoint Online"]:::source
        S2["Google Drive"]:::source
        S3["AWS S3"]:::source
        S4["Local Bulk Archives"]:::source
    end

    subgraph T3["3. Deterministic DAG & Math Verification Gate"]
        direction TB
        G1["DAG Compiler • Little's-Law Concurrency • EWMA Circuit Breaker"]:::gate
        G2["Strict-DAG 2D Layout Sort (Kahn's) • Tables, Equations & PII/Security"]:::gate
        G3["Math Verification: η ≥ 0.998 • D_KL < 1e-4 • 4-Tier Epistemic Audit"]:::gate
        G4["Cryptographic Integrity: UUIDv5 Key • Mutual SHA-256 • Merkle + SQLite Ledger"]:::gate
        G1 --> G2 --> G3 --> G4
    end

    subgraph T4["4. Bijective Dual-Artifact Output"]
        direction LR
        A1["{doc_id}.md\nLossless Text, Tables & Equations\nSHA-256 Cross-Linked"]:::artifact
        A2["{doc_id}.json\nEntities, Graph, RAG Chunks,\nProof Metrics & Tier-4 Audit"]:::artifact
    end

    subgraph T5["5. Enterprise AI & Knowledge Sinks"]
        direction LR
        K1["Qdrant Vector Search"]:::sink
        K2["Neo4j GraphRAG"]:::sink
        K3["Compliance Archives"]:::sink
    end

    T1 --> T2
    T2 --> G1
    G4 --> A1
    G4 --> A2
    A1 --> T5
    A2 --> T5
```

---

## Mathematical & Engineering Guarantees

Every ingested PDF compiles into a cryptographically paired output bundle—**`{doc_id}.md`** + **`{doc_id}.json`**—bound 1-to-1 by filename and mutual **SHA-256 cross-checksums**:

```text
doc_id = UUIDv5(NAMESPACE_OID, SHA256(B) || Normalize(U) || tau)
```

| Guarantee | Enforced Standard | Business & Engineering Impact |
| :--- | :--- | :--- |
| **Bijective Bulk Mapping** | Deterministic `UUIDv5` key + mutual SHA-256 cross-hashes + Merkle tree verification | Zero file collisions across 10,000+ document batches and instant 1-to-1 audit lineage. |
| **Verified Lossless Text** | Token Conservation `η ≥ 0.998` & Unigram/Bigram KL-Divergence `D_KL < 1e-4` | Mathematically proves ≥99.8% of source words, figures, and contract clauses survive intact. |
| **Layout & Table Fidelity** | Strict-DAG 2D bounding-box topological sort (Kahn's algorithm) + structured table/equation parsers | Preserves financial statements, multi-column legal contracts, and formulas without scrambled rows. |
| **Zero-Hallucination Audit** | 4-Tier Epistemic Hierarchy with Tier-4 quarantine logs | Never guesses blurred figures or damaged scans; uncertain spans are isolated for human review. |
| **Resilient Bulk Execution** | EWMA circuit breaker, Little's-Law adaptive concurrency control, and SQLite checkpoint ledger | Survives API rate limits and transient cloud outages with idempotent, resumable checkpoints. |
| **PII & Red-Team Hardening** | Built-in PII detection, prompt-injection security guards, and automated red-team test suite | Separates functional regressions (`exit 1`) from security failures (`exit 2`) in CI/CD. |

<details>
<summary><strong>Deep Dive: What Every Dual-Artifact Pair Contains</strong></summary>

* **`{doc_id}.md`** — Clean, lossless, human- and LLM-readable Markdown preserving headings, paragraphs, nested lists, LaTeX/math equations, multi-column reading order, and complex tables, linked by SHA-256 checksum to its companion JSON.
* **`{doc_id}.json`** — Machine-ready analytical intelligence package containing:
  * Document metadata, source URI lineage, and cryptographic cross-hashes (`UUIDv5`, `SHA-256`, Merkle proof hooks)
  * Extracted entities and graph relationships ready for Neo4j GraphRAG
  * Table-safe RAG chunks ready for Qdrant semantic vector search
  * PII & security inspection flags
  * Measured quality proof metrics (`eta`, unigram/bigram `D_KL`, table recall, DAG ordering verification)
  * Tier-4 epistemic audit entries for any low-confidence OCR spans

</details>

---

## Quick Start (CLI)

### 1. Install Dependencies

```bash
pip install -r requirements.txt
```

### 2. Extract, Verify & Export JSON Schema

```bash
# Bulk-extract local PDFs into paired {doc_id}.md + {doc_id}.json artifacts
python tools/cli.py extract ./pdfs --out ./pdfx_out --workers 8

# Cryptographically verify SHA-256 cross-links, Merkle integrity, and mathematical quality gates
python tools/cli.py verify ./pdfx_out

# Export the strict JSON Schema for downstream pipeline validation
python tools/cli.py schema > document-artifact.schema.json
```

### 3. Run Tests, Red-Team Suite & Evaluation Judges

```bash
# Run unit tests and security red-team scenarios
python -m pytest tests evals/red_team_modes.py -v

# Execute offline evaluation judges + red-team audit (writes evals/report.md)
python evals/judges.py --offline --red-team
```

**CI/CD Exit Codes:**
* `0` — All functional quality gates and security checks passed.
* `1` — Functional / mathematical verification regression detected.
* `2` — Security or red-team policy violation detected.

---

## MCP Federation & OCR Configuration

* **Cloud Sources & Knowledge Sinks:** Remote URIs (`s3://`, `sharepoint://`, `gdrive://`) and knowledge-base sync (`--sink knowledge` for Qdrant & Neo4j) require the connector environment variables documented in [`reference/mcp_integration.md`](reference/mcp_integration.md).
* **OCR Fallback:** For scanned or hybrid PDFs, install Tesseract and set `TESSERACT_CMD`, or set `ANTHROPIC_API_KEY` for vision-assisted fallback governed by the 4-Tier Epistemic Audit policy.

---

## Repository Layout

| Path | Role & Key Modules |
| :--- | :--- |
| `Skill.md` | Agent Skill specification, invocation triggers, mathematical proofs, epistemic definitions, and documented deviations. |
| `features/` | Layout Strict-DAG builder, table & equation extractors, OCR + 4-tier epistemic classifier, entity & graph extraction, table-safe RAG chunking, PII & security scanner, lossless Markdown emitter, quality metrics (`η`, `D_KL`), and per-document pipeline. |
| `scripts/` | Zero-cycle DAG compiler, EWMA circuit breaker, Little's-Law concurrency controller, SQLite checkpoint ledger, telemetry hooks, and cryptographic integrity engine (`doc_id`, SHA-256 cross-hashes, Merkle proofs). |
| `tools/` | MCP router & connectors (SharePoint Online, Google Drive, AWS S3, Qdrant/Neo4j knowledge sink), schemas, bulk worker executor, CLI (`tools/cli.py`), and MCP server. |
| `evals/` | Automated evaluation judges (`evals/judges.py`), red-team scenarios (`evals/red_team_modes.py`), synthetic PDF factory, test vectors, scoring rubric, generated benchmark & audit report (`evals/report.md`). |
| `reference/` | Engineering guidelines, mathematical foundations, MCP integration contracts (`reference/mcp_integration.md`), and agent prompts. |
| `docs/assets/` | Visual benchmark and architecture charts (`benchmark_chart.png`, `architecture_flow.png`). |

---

## Links & Contact

* **Full Agent Skill Specification:** [`Skill.md`](Skill.md)
* **MCP Integration Contracts:** [`reference/mcp_integration.md`](reference/mcp_integration.md)
* **YouTube Demo (dodi):** [Watch on YouTube Shorts](https://youtube.com/shorts/d_22M17a2X8)
* **GitHub:** [@narc-kany](https://github.com/narc-kany)
* **Portfolio:** [narc-kany.github.io](https://narc-kany.github.io/)
* **Technical Deep-Dives:** [Medium (@sivanesh.developer69)](https://medium.com/@sivanesh.developer69)