Metadata-Version: 2.4
Name: nopaddle
Version: 0.1.0
Summary: PaddleOCR-grade document parsing, minus PaddlePaddle, minus PyTorch.
Author: Bei Mi Chen
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/beimichen/nopaddle
Project-URL: Repository, https://github.com/beimichen/nopaddle
Project-URL: Issues, https://github.com/beimichen/nopaddle/issues
Keywords: ocr,pdf,document-parsing,document-ai,layout-analysis,onnx,paddleocr,vlm,table-recognition,formula-recognition
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Topic :: Text Processing
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PyMuPDF>=1.24
Requires-Dist: pillow>=10.0
Requires-Dist: numpy>=1.26
Requires-Dist: opencv-python-headless>=4.9
Requires-Dist: onnxruntime>=1.17
Requires-Dist: huggingface_hub>=0.23
Provides-Extra: onnx
Requires-Dist: tokenizers>=0.20; extra == "onnx"
Provides-Extra: api
Requires-Dist: openai>=1.40; extra == "api"
Provides-Extra: serve
Requires-Dist: fastapi>=0.110; extra == "serve"
Requires-Dist: uvicorn[standard]>=0.29; extra == "serve"
Requires-Dist: python-multipart>=0.0.9; extra == "serve"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Dynamic: license-file

# nopaddle

**PaddleOCR-grade document parsing, minus PaddlePaddle, minus PyTorch, minus the GPU bill.** Turns PDFs into structured, typed regions (text, headings, tables, formulas, figures) in reading order.

> *Being up a creek without a paddle is supposed to be the bad ending. But when the paddle is PaddlePaddle, plus a multi-gigabyte PyTorch stack, plus a GPU that keeps asking for money, losing it is the best thing that can happen to you. Bon voyage.*

PaddleOCR-VL is a genuinely excellent document model that happens to come welded to PaddlePaddle (which drags in PyTorch, which would really love a GPU). nopaddle keeps the model and quietly drops the boat overboard: layout detection is pure ONNX, born-digital prose is read straight from the PDF's own text layer, and the VLM only ever sees the regions that truly need it (math, tables, figures, scanned text). What's left is a small, torch-free, paddle-free library you can `pip install`, run on a laptop, and self-host behind FastAPI.

[![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](./LICENSE)
[![PyPI](https://img.shields.io/pypi/v/nopaddle?color=blue)](https://pypi.org/project/nopaddle/)
![Status: alpha](https://img.shields.io/badge/status-alpha-orange.svg)
![Python: 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)
[![Open in Spaces](https://huggingface.co/datasets/huggingface/badges/resolve/main/open-in-hf-spaces-sm.svg)](https://huggingface.co/spaces/Bei0001/nopaddle)

---

## Why nopaddle

- **Top accuracy, near-zero cost.** nopaddle wraps **PaddleOCR-VL-1.5**, a 0.9B document specialist that scores **94.5** on OmniDocBench v1.5 (**~16 points above Mistral OCR**), and runs it **free, locally**. See [Benchmarks & cost](#benchmarks--cost).
- **All-machine by design.** Both the layout detector **and** the VLM run on `onnxruntime`, so the full pipeline is **truly platform-agnostic**: any OS/CPU (Linux, macOS, Windows), no Apple-Silicon or GPU requirement. The ONNX VLM path is **torch-free *and* transformers-free** (just NumPy/Pillow/onnxruntime/tokenizers).
- **Fast, built for digital PDFs.** Most PDFs are born-digital and carry an exact text layer. nopaddle reads prose **straight from that layer** (≈1 ms/region, no model) and sends *only* the visual minority (math, tables, figures, scanned regions) to the VLM. That's ~**2.9× fewer VLM calls** on typical documents, so most pages come back in milliseconds.
- **Tiny & dependency-light.** **No PyTorch, no PaddlePaddle, no CUDA wheels**: the whole core install is **~350 MB** (PyMuPDF, Pillow, NumPy, OpenCV-headless, onnxruntime) versus the multi-GB GPU stacks typical of VLM document parsers. Runs on a CPU-only laptop; the VLM loads lazily and is freed between documents.
- **Free, with an optional cheap fallback.** Everything runs locally for free. You can optionally offload just the math/table/figure minority to a hosted commercial VLM; prose stays free and local.
- **Self-hostable.** A FastAPI service and Docker image ship for drop-in `POST /parse` document parsing.

---

## Benchmarks & cost

> **TL;DR:** the top score on OmniDocBench v1.5 (**94.5 overall**), run locally for **$0**, or via a hosted API at a fraction of Mistral OCR's price.

nopaddle wraps **PaddleOCR-VL-1.5**, a 0.9B document-parsing specialist that tops [OmniDocBench](https://github.com/opendatalab/OmniDocBench), and runs it **free locally** (ONNX) or via a cheap hosted API. Accuracy below is PaddleOCR-VL's **published** OmniDocBench v1.5 score (we wrap that model); API cost is **estimated**, local cost is genuinely $0. ([caveats](#a-note-on-these-numbers))

### Accuracy: OmniDocBench v1.5 *(higher is better)*

![OmniDocBench v1.5 Overall: nopaddle vs others](docs/benchmarks/accuracy.png)

| System | Overall ↑ | Tables · TEDS ↑ | Text · edit ↓ |
| --- | --- | --- | --- |
| **PaddleOCR-VL-1.5 (nopaddle)** | **94.50** | **92.76** | **0.035** |
| MinerU2.5 | 90.67 | 88.22 | 0.047 |
| Gemini-3 Pro | 90.33 | 88.28 | 0.065 |
| Gemini-2.5 Pro | 88.03 | 85.71 | 0.075 |
| Mistral OCR (`mistral-ocr-latest`) | 78.83 | 70.03 | 0.164 |
| GPT-4o | 75.02 | 67.07 | 0.217 |

The 0.9B specialist beats **Mistral OCR by +15.7 points overall**, widest on **tables** (92.76 vs 70.03 TEDS) and **text fidelity** (0.035 vs 0.164 edit distance, ~4.7× fewer corrections). Source: PaddleOCR-VL-1.5 report ([arXiv 2601.21957](https://arxiv.org/abs/2601.21957), Table 2); the Mistral OCR row is the PaddleOCR team's measurement, not Mistral's self-report.

### Cost: USD per 1,000 pages *(lower is better)*

![Cost per 1,000 pages: nopaddle vs Mistral OCR](docs/benchmarks/cost.png)

| Path | $/1,000 pages | How |
| --- | --- | --- |
| **nopaddle local (ONNX)** | **$0.00** | runs on your own hardware, free **and** offline |
| nopaddle API, born-digital | ~$0.04-0.14 | only the visual minority hits the VLM; prose is read from the text layer |
| nopaddle API, Gemini 2.5 Flash-Lite (full-page) | ~$0.71 | ~1.1k image + 1.5k output tok/page ([Gemini pricing](https://ai.google.dev/gemini-api/docs/pricing)); ~$0.36 batch |
| Mistral OCR (batch / standard) | $1.00 / $2.00 | flat per page ([Mistral pricing](https://mistral.ai/pricing)) |

So you get **higher accuracy at $0** locally, or on the API path a **fraction of Mistral OCR's price**, *especially* on born-digital documents where the text-layer fast path keeps prose off the paid VLM entirely.

#### A note on these numbers

- **Accuracy is piggybacked, not re-run.** It's PaddleOCR-VL's *published* score for the reference weights; nopaddle runs the **ONNX** export (quantization can shift it slightly; we haven't independently re-benchmarked it). Read it as *"nopaddle wraps the model that scores 94.50."*
- **Metric directions differ.** `Overall` / `TEDS` are higher-better ↑; `Text · edit` is normalized edit distance, lower-better ↓ (0.035 ≈ near-perfect).
- **The Mistral OCR row is a competitor's measurement.** Mistral *self-reports* ~94.9 on its own internal set; treat vendor self-reports as claims, and don't mix the two scales.
- **API cost is estimated** (varies with page complexity / output length); the **local path is exactly $0**, and Mistral's per-page rate is official.
- "Mistral OCR" here is **OCR 3** (`mistral-ocr-latest`), not the Mixtral chat model.

---

## Quickstart

Install with the all-machine ONNX extra:

```bash
pip install "nopaddle[onnx]"
```

> `[onnx]` is the platform-agnostic local backend; it runs on any OS/CPU (Linux, macOS, Windows), no GPU required.
>
> Before the first PyPI release, install from source instead: `pip install "nopaddle[onnx] @ git+https://github.com/beimichen/nopaddle"`.

Parse a PDF from the command line:

```bash
python -m nopaddle file.pdf                       # JSON to stdout
python -m nopaddle file.pdf --format markdown      # Markdown to stdout
python -m nopaddle file.pdf -o out.json            # write to a file
```

Or from Python:

```python
from nopaddle import parse_pdf

doc = parse_pdf("file.pdf")          # auto-selects a runtime, frees the VLM when done
print(doc.to_markdown())             # or doc.to_json()
```

`parse_pdf` returns a `ParsedDocument`: an ordered list of `Page`s, each holding typed `Region`s with bounding boxes normalized to a resolution-independent 0-1000 scale. Serialize it with `.to_dict()`, `.to_json()`, or `.to_markdown()`. A single region serializes like:

```json
{
  "type": "section_header",
  "content": "ABSTRACT",
  "bbox": {"x_min": 230, "y_min": 293, "x_max": 769, "y_max": 312},
  "page": 1,
  "confidence": 0.99
}
```

Region `type`s include `title`, `section_header`, `text`, `table`, `formula`, `figure`, `caption`, and `footnote`.

---

## Runtimes

The parser core is written against a single `(image, prompt) -> text` backend seam and never imports a runtime directly. Pick one with `runtime=` (or `--runtime`), or let `"auto"` choose for you.

| Runtime  | Backend                  | Where it runs               | Status      |
| -------- | ------------------------ | --------------------------- | ----------- |
| `onnx`   | onnxruntime (torch-free) | All machines (platform-agnostic) | **Working** |
| `api`    | OpenAI / Gemini (hosted) | Anywhere (optional)              | **Working** |
| `none`   | *(no VLM)*               | Anywhere                    | **Working** |

**Auto-selection.** `runtime="auto"` (the default) resolves to **`onnx`**, the platform-agnostic local backend that runs anywhere. Override deployment-wide with `NOPADDLE_RUNTIME` (e.g. `api`).

**`runtime="none"`** runs layout detection plus the born-digital text-layer fast path with **zero model weights**: prose and figure bounding boxes come out fully, while math/table/scanned regions are emitted as bbox-only placeholders. This is the lightest way to parse a born-digital PDF.

### ONNX precision (quantization)

The `onnx` backend reuses the [`onnx-community/PaddleOCR-VL-1.5-ONNX`](https://huggingface.co/onnx-community/PaddleOCR-VL-1.5-ONNX) export (Apache-2.0) and runs a host-side, KV-cached decode loop on raw `onnxruntime`. Pick the precision; the package **downloads and loads the matching graphs automatically** on first use:

| `quantization`  | Size (3 graphs) | Notes                                                |
| --------------- | --------------- | ---------------------------------------------------- |
| `fp32`          | ~3.6 GB         | full precision; most literal output (e.g. LaTeX units) |
| `q8` *(default)*| ~1.2 GB         | int8; validated word-for-word                        |
| `quint8`        | ~1.2 GB         | uint8 decoder; vision falls back to q8               |
| `q4`            | smallest        | int4; fidelity not yet validated                     |

Set it per call (`parse_pdf(..., quantization="fp32")`, `make_parser("onnx", quantization=...)`), on the CLI (`--quantization fp32`), per request (`/parse?quantization=fp32`), or deployment-wide with `NOPADDLE_ONNX_QUANT`. There is no fp16 variant in the export; on CPU `fp32` is the high-fidelity choice (fp16 mostly helps on GPU).

### API providers (hosted, optional)

`runtime="api"` sends each VLM-bound region to a hosted vision model over the OpenAI-compatible Chat API. Models are a **curated, vision-capable allow-list** (the provider is inferred from the model); set the provider's key via env:

| Model (`--model` / `model=`)        | Provider | Key env var                            |
| ----------------------------------- | -------- | -------------------------------------- |
| `gemini-2.5-flash-lite` *(default)* | Gemini   | `GEMINI_API_KEY` (or `GOOGLE_API_KEY`) |
| `gemini-2.5-flash`, `gemini-2.5-pro` | Gemini  | `GEMINI_API_KEY`                       |
| `gpt-4o-mini`, `gpt-5.4-mini`, `gpt-4o`, `gpt-5.5` | OpenAI | `OPENAI_API_KEY`         |

```bash
pip install "nopaddle[api]"
GEMINI_API_KEY=... nopaddle doc.pdf --runtime api --model gemini-2.5-flash-lite --format markdown
```

> DeepSeek's hosted API is text-only (no vision), so it's intentionally not in the list. For a self-hosted / third-party OpenAI-compatible vision endpoint (OpenRouter, vLLM, DeepSeek-VL, …), pass a custom `base_url` (or `NOPADDLE_API_BASE_URL`) with any model id.

**Error handling.** Failures are classified **transient** vs **fatal** with a named `ApiErrorKind` (e.g. `RATE_LIMIT (429)` vs `INSUFFICIENT_QUOTA (429)`):
- **Transient** (rate-limit, 5xx, timeout, network) → retried with backoff; if it still fails, that one region degrades to a placeholder and the document keeps parsing.
- **Fatal** (bad/missing key, depleted credits/quota, unknown model, bad request) → the parse aborts immediately with an actionable message, e.g. `[gemini INSUFFICIENT_QUOTA (429)] quota/credits exhausted … add credits`. Catch `nopaddle.FatalBackendError` / `nopaddle.TransientBackendError` in code.

### Concurrency

Within a page, the VLM-bound regions (math, tables, figures, scanned text) can be processed in parallel; set it via `concurrency=N` (`parse_pdf`/`make_parser`), `--concurrency N`, `?concurrency=N`, or `NOPADDLE_CONCURRENCY`. Default is `1` (sequential).

**When to use it.** It's a win where the per-region work is **I/O-bound**, i.e. the **`api`** backend, where each region is an HTTP round-trip to OpenAI/Gemini, so firing them concurrently overlaps the network latency. The payoff scales with how many regions on a page hit the VLM:
- A **scanned page** (every region goes to the VLM) or a **dense page of formulas/tables** benefits most: e.g. a scanned 4-region page went **~12s → ~4.5s at `concurrency=8`** (≈2.6×).
- A typical **born-digital** page barely touches the VLM (prose is read from the text layer), so there's little to parallelize, and that's fine.
- The local **`onnx`** backend is compute-bound, so concurrency helps it far less, and only up to your CPU/GPU headroom.

**Guarantees.** Reading order is **always preserved** regardless of completion order. A **fatal** error (bad key, depleted credits) still aborts the whole parse with an actionable message; a **transient** one degrades just that region after retries. Parallelism is applied only to thread-safe backends.

---

## The born-digital fast path

Most real-world PDFs are *born-digital*: exported from LaTeX, Word, or a browser, they carry an exact, machine-readable text layer. Running a VLM over that prose is slow and pointless; the text is already there.

nopaddle exploits this with a per-page, data-driven gate (no flags):

1. **Layout pass.** PP-DocLayoutV3 (ONNX) detects every region and its type.
2. **Born-digital probe.** If a page exposes enough extractable text (`NOPADDLE_BORN_DIGITAL_MIN_CHARS`, default 100), it's treated as born-digital.
3. **Hybrid extraction.** On born-digital pages, **text/heading regions are read straight from the PDF text layer**: exact, instant, free. Only the regions a text layer can't represent (**formulas, tables, figures, and scanned/empty regions**) are cropped and sent to the VLM.

Because prose is the overwhelming majority of a typical page, this routes only the visual minority to the model (about **2.9× fewer VLM calls** on born-digital documents) while keeping the same structured output. Scanned or sparse pages fall back to the VLM automatically, so quality never depends on a guess.

---

## FastAPI & Docker

Install the service extra and run the API locally:

```bash
pip install "nopaddle[serve,onnx]"
nopaddle-serve                       # or: uvicorn nopaddle.server.main:app --host 0.0.0.0 --port 8000
```

POST a PDF and get structured JSON back:

```bash
curl -sS -X POST http://127.0.0.1:8000/parse -F "file=@mydoc.pdf"
```

A Docker image is provided for self-hosting:

```bash
docker build -t nopaddle -f docker/Dockerfile .
docker run --rm -p 8000:8000 nopaddle
```

The server loads models lazily and frees the detector + VLM between requests, so a long-running instance keeps a small resident footprint.

---

## Models

nopaddle pulls models from the Hugging Face Hub on first use and caches them on disk.

| Role           | Model                                            | Notes                                  |
| -------------- | ------------------------------------------------ | -------------------------------------- |
| Layout         | `Bei0001/PP-DocLayoutV3-ONNX`                     | ONNX detector, runs everywhere         |
| VLM            | `onnx-community/PaddleOCR-VL-1.5-ONNX`            | torch-free ONNX; `quantization=` picks precision (q8 default) |

Configuration via environment variables:

| Variable                          | Purpose                                                        |
| --------------------------------- | ------------------------------------------------------------- |
| `MODEL_CACHE_DIR`                 | Where downloaded models live (default: `~/.cache/nopaddle/models`). |
| `HF_TOKEN`                        | Hugging Face token, only needed for gated/private repos.     |
| `NOPADDLE_RUNTIME`                | Override the auto-selected runtime deployment-wide.           |
| `NOPADDLE_ONNX_QUANT`             | ONNX VLM precision: `fp32` / `q8` (default) / `q4` / `quint8`. |
| `NOPADDLE_API_MODEL`              | Default hosted model for `runtime=api` (e.g. `gemini-2.5-flash-lite`). |
| `GEMINI_API_KEY` / `OPENAI_API_KEY` | API key for the chosen `runtime=api` provider.              |
| `NOPADDLE_API_BASE_URL`           | Custom OpenAI-compatible vision endpoint (advanced).         |
| `NOPADDLE_CONCURRENCY`            | Max VLM regions per page to run concurrently (default 1).    |
| `NOPADDLE_BORN_DIGITAL_MIN_CHARS` | Text threshold for the born-digital fast path (default 100).  |
| `NOPADDLE_RENDER_SCALE`           | Page→image render scale for the VLM (default 2.0 ≈ 144 DPI).  |
| `NOPADDLE_LAYOUT_REPO`            | Point the layout detector at a fork/mirror.                   |

---

## Status

This is an early (alpha) release, and it's honest about what's done:

- ✅ **Layout detection (ONNX)**: works on all machines, today.
- ✅ **Born-digital text-layer fast path**: works on all machines with no VLM weights.
- ✅ **Cross-platform ONNX VLM backend**: runs on all machines via raw `onnxruntime`, **torch- and transformers-free**. Reuses `onnx-community/PaddleOCR-VL-1.5-ONNX` with a host-side KV-cached decode loop; the SigLIP preprocessor is a numpy/PIL port validated byte-for-byte against the reference. Validated at **q8** (word-for-word OCR + tables + formulas); `q4`/`quint8` are wired but their fidelity isn't validated yet, and only CPU has been exercised (CUDA is coded but untested). See [`docs/onnx_port.md`](./docs/onnx_port.md).
- ✅ **Hosted API backend (OpenAI / Gemini)**: optional `runtime="api"` with a curated model allow-list, a transient/fatal error taxonomy, and per-page concurrency. Validated against real Gemini (formula + table OCR). See [`docs/api_backend.md`](./docs/api_backend.md).

In short: **the full pipeline (layout, born-digital fast path, and the ONNX VLM) works on any machine right now**, torch-free, with an optional hosted-API backend. Remaining polish: validating the smaller ONNX quantizations and the CUDA path.

---

## License

[Apache-2.0](./LICENSE).

## Acknowledgements

nopaddle stands on excellent open work from the PaddlePaddle team:

- **[PaddleOCR-VL](https://github.com/PaddlePaddle/PaddleOCR)**: the vision-language OCR model nopaddle wraps for math, tables, figures, and scanned text.
- **PP-DocLayoutV3**: the document layout detector, re-exported to ONNX for portable, runtime-light layout analysis.

nopaddle is an independent re-packaging that runs these models without PaddlePaddle or PyTorch; it is not affiliated with or endorsed by the PaddlePaddle project.
