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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: cc-by-nc-4.0
|
| 3 |
+
library_name: onnx
|
| 4 |
+
pipeline_tag: image-classification
|
| 5 |
+
tags:
|
| 6 |
+
- onnx
|
| 7 |
+
- ocr
|
| 8 |
+
- document-ai
|
| 9 |
+
- document-layout
|
| 10 |
+
- image-quality
|
| 11 |
+
- image-classification
|
| 12 |
+
datasets:
|
| 13 |
+
- allenai/olmOCR-mix-0225
|
| 14 |
---
|
| 15 |
+
|
| 16 |
+
# OCR Crop Quality Classifier (ONNX)
|
| 17 |
+
|
| 18 |
+
A lightweight binary classifier that tells whether a **document region crop** is legible enough to
|
| 19 |
+
be sent to an OCR model. It labels each crop `good` or `bad`.
|
| 20 |
+
|
| 21 |
+
It is meant to sit between a layout detector and a (vision-language) OCR model. Crops are produced
|
| 22 |
+
by a detector such as [`Inceptive/PP-DocLayoutV3-ONNX`](https://huggingface.co/Inceptive/PP-DocLayoutV3-ONNX),
|
| 23 |
+
and this model flags the ones that are too blurry, pixelated or compression-damaged. The pipeline can
|
| 24 |
+
then skip those regions instead of running expensive inference on them, since unreadable regions
|
| 25 |
+
are a common source of hallucinated OCR output.
|
| 26 |
+
|
| 27 |
+
| | |
|
| 28 |
+
|---|---|
|
| 29 |
+
| **Task** | Binary image classification (`bad` / `good`) |
|
| 30 |
+
| **Format** | ONNX, opset 17, single file (no external-data sidecar) |
|
| 31 |
+
| **Size** | 1.5 MB, 390,370 parameters |
|
| 32 |
+
| **Input** | `input_IMAGE`, `float32[N, 3, 640, 640]`, NCHW, RGB, normalized |
|
| 33 |
+
| **Output** | `output_0`, `float32[N, 2]`, softmax probabilities, order `[bad, good]` |
|
| 34 |
+
| **Runtime** | Any ONNX Runtime execution provider (CPU is fast enough for per-crop use) |
|
| 35 |
+
|
| 36 |
+
## Intended use
|
| 37 |
+
|
| 38 |
+
- **In scope:** crops of printed or scanned document pages (text blocks, titles, tables, form
|
| 39 |
+
fields, figures with text), as produced by a document layout detector. Use it to decide whether a
|
| 40 |
+
region should be OCR'd or skipped / flagged for review.
|
| 41 |
+
- **Out of scope:** natural-scene photos, general-purpose image quality assessment (IQA) or
|
| 42 |
+
aesthetic scoring, and full-resolution pages when you need a per-region decision. Also out of
|
| 43 |
+
scope: any decision about a document's *content*. The model only judges visual legibility.
|
| 44 |
+
|
| 45 |
+
## Model inputs and outputs
|
| 46 |
+
|
| 47 |
+
### Input: `input_IMAGE`
|
| 48 |
+
|
| 49 |
+
`float32` tensor of shape `[N, 3, 640, 640]`, with a dynamic batch dimension `N`. The image must be
|
| 50 |
+
preprocessed **exactly** as during training:
|
| 51 |
+
|
| 52 |
+
1. **Convert to RGB.** If you load images with OpenCV, convert BGR β RGB first.
|
| 53 |
+
2. **Downscale only if needed.** If the longest side is larger than 640 px, resize so that the
|
| 54 |
+
longest side is exactly 640 px, **keeping the aspect ratio**. Images that already fit are
|
| 55 |
+
**never upscaled**.
|
| 56 |
+
3. **Center and zero-pad** the image onto a 640 Γ 640 canvas, filling every channel with `0`
|
| 57 |
+
(black). Padding happens in pixel space, *before* normalization.
|
| 58 |
+
4. **Scale** pixel values to `[0, 1]` (divide by 255).
|
| 59 |
+
5. **Normalize** with the ImageNet statistics: `mean = [0.485, 0.456, 0.406]`,
|
| 60 |
+
`std = [0.229, 0.224, 0.225]`, per channel.
|
| 61 |
+
6. **Transpose** HWC β CHW and add the batch dimension.
|
| 62 |
+
|
| 63 |
+
> Do not stretch crops to 640 Γ 640. A plain resize distorts the aspect ratio and upsamples small
|
| 64 |
+
> crops, which the model never saw during training, and shifts its scores.
|
| 65 |
+
|
| 66 |
+
### Output: `output_0`
|
| 67 |
+
|
| 68 |
+
`float32` tensor of shape `[N, 2]`, holding class probabilities in the order `["bad", "good"]`. The
|
| 69 |
+
graph already ends with a `Softmax`, so do **not** apply another one.
|
| 70 |
+
|
| 71 |
+
The decision rule we use is `P(good) < 0.5 β low quality`. Raise the threshold to skip more regions
|
| 72 |
+
(fewer hallucinations, more missed text), or lower it to keep more.
|
| 73 |
+
|
| 74 |
+
## How to use
|
| 75 |
+
|
| 76 |
+
Install the dependencies:
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
pip install onnxruntime numpy pillow huggingface_hub
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Classify one crop:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
import numpy as np
|
| 86 |
+
import onnxruntime as ort
|
| 87 |
+
from huggingface_hub import hf_hub_download
|
| 88 |
+
from PIL import Image
|
| 89 |
+
|
| 90 |
+
REPO_ID = "Inceptive/document-gate-keeper-v0"
|
| 91 |
+
MODEL_FILE = "model.onnx"
|
| 92 |
+
|
| 93 |
+
SIZE = 640
|
| 94 |
+
MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
|
| 95 |
+
STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
|
| 96 |
+
CLASSES = ("bad", "good")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def preprocess(image: Image.Image) -> np.ndarray:
|
| 100 |
+
"""PIL image -> float32 [1, 3, 640, 640] tensor, as used during training."""
|
| 101 |
+
image = image.convert("RGB")
|
| 102 |
+
|
| 103 |
+
# Downscale (keeping the aspect ratio) only if the image is larger than 640 px; never upscale.
|
| 104 |
+
w, h = image.size
|
| 105 |
+
scale = SIZE / max(w, h)
|
| 106 |
+
if scale < 1.0:
|
| 107 |
+
image = image.resize((max(1, round(w * scale)), max(1, round(h * scale))), Image.BILINEAR)
|
| 108 |
+
|
| 109 |
+
# Center the image on a black 640x640 canvas: zero padding on all channels, before normalization.
|
| 110 |
+
canvas = Image.new("RGB", (SIZE, SIZE), (0, 0, 0))
|
| 111 |
+
canvas.paste(image, ((SIZE - image.width) // 2, (SIZE - image.height) // 2))
|
| 112 |
+
|
| 113 |
+
x = np.asarray(canvas, dtype=np.float32) / 255.0 # HWC, [0, 1]
|
| 114 |
+
x = (x - MEAN) / STD # ImageNet normalization
|
| 115 |
+
return x.transpose(2, 0, 1)[np.newaxis] # NCHW
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
model_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILE)
|
| 119 |
+
session = ort.InferenceSession(
|
| 120 |
+
model_path,
|
| 121 |
+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"], # falls back to CPU
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
image = Image.open("crop.png")
|
| 125 |
+
probs = session.run(["output_0"], {"input_IMAGE": preprocess(image)})[0][0] # already softmaxed
|
| 126 |
+
|
| 127 |
+
p_bad, p_good = float(probs[0]), float(probs[1])
|
| 128 |
+
print(f"P(bad)={p_bad:.3f} P(good)={p_good:.3f} -> {CLASSES[int(probs.argmax())]}")
|
| 129 |
+
|
| 130 |
+
GOOD_QUALITY_THRESHOLD = 0.5
|
| 131 |
+
if p_good < GOOD_QUALITY_THRESHOLD:
|
| 132 |
+
print("Low-quality crop: skip OCR or flag it for review.")
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
Classify several crops in one call (the batch dimension is dynamic):
|
| 136 |
+
|
| 137 |
+
```python
|
| 138 |
+
crops = [Image.open(p) for p in ["region_0.png", "region_1.png", "region_2.png"]]
|
| 139 |
+
batch = np.concatenate([preprocess(c) for c in crops]) # [N, 3, 640, 640]
|
| 140 |
+
probs = session.run(["output_0"], {"input_IMAGE": batch})[0] # [N, 2]
|
| 141 |
+
|
| 142 |
+
for path, (p_bad, p_good) in zip(["region_0.png", "region_1.png", "region_2.png"], probs):
|
| 143 |
+
print(path, "good" if p_good >= GOOD_QUALITY_THRESHOLD else "bad", f"(P(good)={p_good:.3f})")
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
Each crop is padded to 640 Γ 640, so a batch of `N` crops costs `N Γ 3 Γ 640 Γ 640 Γ 4` bytes of
|
| 147 |
+
input (β 4.9 MB per crop). Batch in moderate chunks.
|
| 148 |
+
|
| 149 |
+
**With a layout detector:** run [`Inceptive/PP-DocLayoutV3-ONNX`](https://huggingface.co/Inceptive/PP-DocLayoutV3-ONNX)
|
| 150 |
+
on the page, crop each detected box from the page image at its original resolution, and pass each
|
| 151 |
+
crop through `preprocess` above. Do not run the classifier on the detector's own resized input.
|
| 152 |
+
|
| 153 |
+
## Model architecture
|
| 154 |
+
|
| 155 |
+
A small convolutional network:
|
| 156 |
+
|
| 157 |
+
| Stage | Layers | Output channels |
|
| 158 |
+
|---|---|---|
|
| 159 |
+
| Block 1 | Conv 3Γ3 (stride 1, same padding) β BatchNorm β ReLU β MaxPool 2Γ2 | 32 |
|
| 160 |
+
| Block 2 | Conv 3Γ3 β BatchNorm β ReLU β MaxPool 2Γ2 | 64 |
|
| 161 |
+
| Block 3 | Conv 3Γ3 β BatchNorm β ReLU β MaxPool 2Γ2 | 128 |
|
| 162 |
+
| Block 4 | Conv 3Γ3 β BatchNorm β ReLU β MaxPool 2Γ2 | 256 |
|
| 163 |
+
| Head | Global average pooling β Flatten β Dropout β Linear (256 β 2) β Softmax | 2 |
|
| 164 |
+
|
| 165 |
+
The preprocessing contract is also embedded in the ONNX file's `metadata_props` (`input_size`,
|
| 166 |
+
`input_layout`, `input_scale`, `normalization_mean`, `normalization_std`, `classes`):
|
| 167 |
+
|
| 168 |
+
```python
|
| 169 |
+
import onnx
|
| 170 |
+
print({p.key: p.value for p in onnx.load(model_path).metadata_props})
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
## Training data
|
| 174 |
+
|
| 175 |
+
The training set is synthetic and was built from two public document datasets:
|
| 176 |
+
|
| 177 |
+
- [**olmOCR**](https://huggingface.co/datasets/allenai/olmOCR-mix-0225) (Allen Institute for AI),
|
| 178 |
+
a large and diverse collection of PDF pages.
|
| 179 |
+
- [**FUNSD**](https://guillaumejaume.github.io/FUNSD/), noisy scanned forms.
|
| 180 |
+
|
| 181 |
+
Construction:
|
| 182 |
+
|
| 183 |
+
1. **Region cropping.** Every page was run through
|
| 184 |
+
[`Inceptive/PP-DocLayoutV3-ONNX`](https://huggingface.co/Inceptive/PP-DocLayoutV3-ONNX), and each
|
| 185 |
+
detected layout region was cropped. The classifier therefore sees the same kind of input it gets
|
| 186 |
+
at inference time in an OCR pipeline.
|
| 187 |
+
2. **Quality degradation.** Each crop was degraded by applying **successive upscales and
|
| 188 |
+
downscales** (resampling artifacts and loss of fine detail) and **JPEG compression** (blocking
|
| 189 |
+
and ringing artifacts).
|
| 190 |
+
3. **Labelling.** Original, untouched crops are labelled `good`. Degraded crops are labelled `bad`.
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
## Training procedure
|
| 194 |
+
|
| 195 |
+
- **Epochs:** 10 full passes over the generated dataset.
|
| 196 |
+
- **Input pipeline:** the preprocessing described above (RGB, downscale-only resize, centered zero
|
| 197 |
+
padding to 640 Γ 640, ImageNet normalization).
|
| 198 |
+
|
| 199 |
+
## Limitations and biases
|
| 200 |
+
|
| 201 |
+
- **Synthetic degradations only.** "Bad" means *resampled and/or JPEG-compressed*. The model was
|
| 202 |
+
not trained on motion blur, defocus, noise, low contrast, skew, show-through, stains or
|
| 203 |
+
handwriting quality, and it may misjudge real-world scans that fail in those ways.
|
| 204 |
+
- **Domain.** The source pages come from olmOCR's PDF mix and FUNSD's English forms. Other
|
| 205 |
+
scripts, unusual layouts or very different rendering resolutions are less well covered.
|
| 206 |
+
- **Mostly blank or extreme crops.** A crop that is mostly empty margin, or very thin and elongated
|
| 207 |
+
(and so mostly padding after letterboxing), carries little signal and may be scored `bad` even
|
| 208 |
+
when it is clean. Use it on tight layout-detector crops, not on arbitrary rectangles.
|
| 209 |
+
- **Small crops are not enlarged.** A tiny crop occupies only a small part of the 640 Γ 640 canvas.
|
| 210 |
+
That matches training, but the model's confidence on very small regions is lower.
|
| 211 |
+
- **Probabilities are not calibrated.** Tune the `P(good)` threshold on your own data if the
|
| 212 |
+
cost of skipping a region differs from the cost of OCR'ing a bad one.
|
| 213 |
+
|
| 214 |
+
## License
|
| 215 |
+
|
| 216 |
+
This model is released under **[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/)**:
|
| 217 |
+
non-commercial use only. This follows the terms of its training data:
|
| 218 |
+
|
| 219 |
+
- **FUNSD** is available for non-commercial, research and educational purposes only.
|
| 220 |
+
- **olmOCR-mix** is released by AI2 under ODC-BY 1.0, which requires attribution (see Citation).
|
| 221 |
+
|
| 222 |
+
## Future work
|
| 223 |
+
|
| 224 |
+
Future versions will improve
|
| 225 |
+
|
| 226 |
+
## Citation
|
| 227 |
+
|
| 228 |
+
If you use this model, please also cite the datasets it was trained on:
|
| 229 |
+
|
| 230 |
+
```bibtex
|
| 231 |
+
@misc{poznanski2025olmocr,
|
| 232 |
+
title = {olmOCR: Unlocking Trillions of Tokens in PDFs with Vision Language Models},
|
| 233 |
+
author = {Jake Poznanski and Jon Borchardt and Jason Dunkelberger and Regan Huff and Daniel Lin and Aman Rangapur and Christopher Wilhelm and Kyle Lo and Luca Soldaini},
|
| 234 |
+
year = {2025},
|
| 235 |
+
eprint = {2502.18443},
|
| 236 |
+
archivePrefix = {arXiv},
|
| 237 |
+
primaryClass = {cs.CL}
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
@inproceedings{jaume2019funsd,
|
| 241 |
+
title = {FUNSD: A Dataset for Form Understanding in Noisy Scanned Documents},
|
| 242 |
+
author = {Guillaume Jaume and Hazim Kemal Ekenel and Jean-Philippe Thiran},
|
| 243 |
+
booktitle = {2019 International Conference on Document Analysis and Recognition Workshops (ICDARW)},
|
| 244 |
+
year = {2019}
|
| 245 |
+
}
|
| 246 |
+
```
|
model.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d1c70de5bf0ee106502462d1d9c91d63a590aa9d2bf77e319bb075f0c8fcb137
|
| 3 |
+
size 1567459
|