File size: 10,820 Bytes
a351116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614bbbe
a351116
196316d
a351116
614bbbe
a351116
62c242b
196316d
a351116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196316d
a351116
196316d
a351116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196316d
614bbbe
 
 
 
62c242b
614bbbe
 
 
 
 
 
 
 
 
a351116
 
 
 
 
 
 
 
 
614bbbe
a351116
 
614bbbe
 
 
a351116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614bbbe
a351116
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
---
license: apache-2.0
library_name: timm
pipeline_tag: image-classification
base_model: timm/hgnetv2_b0.ssld_stage2_ft_in1k
language:
  - multilingual
  - en
  - de
  - fr
  - es
  - pt
  - it
  - nl
  - sv
  - pl
  - tr
  - id
  - vi
  - ru
  - uk
  - el
  - ar
  - fa
  - ur
  - he
  - hi
  - bn
  - gu
  - ta
  - te
  - kn
  - ml
  - th
  - km
  - my
  - ka
  - hy
  - am
  - zh
  - ja
  - ko
tags:
  - ocr
  - script-identification
  - page-classification
  - document-ai
  - multi-label
  - onnx
  - glam
  - knowledge-distillation
  - hf_jobs
---

# Page script ID (HGNetV2-B0)

The higher-accuracy sibling to [`davanstrien/page-script-id`](https://huggingface.co/davanstrien/page-script-id) (MobileNetV4-Small). It looks at a full document page (greyscale, `640 Γ— 640`) and returns an independent calibrated probability for each of 21 writing scripts, or `unknown`, without running OCR.

Built on **`hgnetv2_b0.ssld_stage2_ft_in1k`** (3.99M parameters, 16.0 MB ONNX): **~79 ms** on 1 CPU thread / **~28–36 ms** on 4 threads (~10Γ— faster than ConvNeXt-Tiny on CPU), **621 pages/s** on an A10G in `bf16`. Compared to the 2.52M MobileNetV4-Small variant, it adds **+3.2 pts on photographed documents (88.0%, 97.6% 1-script accuracy)**, higher accuracy on government scans (**90.9%**), **100%** on square-padded Kannada crops, and **91.3%** refusal on real held-out 2026 Sinhala PDFs.

- **Try it live:** [Page Script ID Demo Space](https://huggingface.co/spaces/davanstrien/page-script-id-demo) (side-by-side CPU comparison with MobileNetV4-Small)
- **Faster sibling:** [`davanstrien/page-script-id`](https://huggingface.co/davanstrien/page-script-id) (MobileNetV4-Small, 2.52M, 33 ms 1t / 11 ms 4t CPU, 1,773 pages/s A10G)

> **Check the thresholds on your own pages.** The default cut-offs (`0.55` for a script, `0.7314` for `unknown`) were chosen on held-out web-PDF validation pages (95% coverage). On government documents this refuses ~10% and on photographed documents ~29% (with 97.6% accuracy on answered single-script pages). Adjust `unknown_threshold` and `script_threshold` in `config.json` on a sample of your own collection.

**21 scripts:** Arabic (`Arab`), Armenian (`Armn`), Bengali (`Beng`), Cyrillic (`Cyrl`), Devanagari (`Deva`), Ethiopic (`Ethi`), Georgian (`Geor`), Greek (`Grek`), Gujarati (`Gujr`), Han (`Hani`), Hangul (`Hang`), Hebrew (`Hebr`), Japanese (`Jpan`), Kannada (`Knda`), Khmer (`Khmr`), Latin (`Latn`), Malayalam (`Mlym`), Myanmar (`Mymr`), Tamil (`Taml`), Telugu (`Telu`), Thai (`Thai`).

## Quick start (ONNX Runtime)

```bash
pip install onnxruntime pillow numpy
python example.py page.jpg
python example.py --pad crop.jpg     # for wide text-block crops
python example.py --mixed page.jpg   # 0.50 threshold for mixed-script search
```

Preprocessing: greyscale, bilinear squash to `640 Γ— 640`, float32 `0..255`. ImageNet normalisation, temperature (`1.10`), and sigmoid are baked inside `model.onnx`, which outputs the 21 calibrated probabilities directly.

## Use with `timm`

`model.safetensors` holds the same weights for [timm](https://github.com/huggingface/pytorch-image-models) (`hgnetv2_b0`, 21 outputs in `label_names` order). Apply `sigmoid(logits / 1.10)` to its output logits.

```python
import json
import sys
from pathlib import Path

import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

model_id = "hf-hub:davanstrien/page-script-id-hgnet"
model = timm.create_model(model_id, pretrained=True).eval()
cfg = json.loads(Path(hf_hub_download("davanstrien/page-script-id-hgnet", "config.json")).read_text())["inference"]
size = cfg["input_size"]
mean = torch.tensor(model.pretrained_cfg["mean"]).view(3, 1, 1)
std = torch.tensor(model.pretrained_cfg["std"]).view(3, 1, 1)


def load_page(path):
    im = Image.open(path)
    if im.format == "JPEG":
        im.draft("L", (2 * size, 2 * size))
    grey = im.convert("L").resize((size, size), Image.BILINEAR)
    x = torch.frombuffer(bytearray(grey.tobytes()), dtype=torch.uint8).float().view(1, size, size) / 255
    return (x.expand(3, -1, -1) - mean) / std


with torch.inference_mode():
    x = torch.stack([load_page(p) for p in sys.argv[1:]])
    probs = torch.sigmoid(model(x) / cfg["temperature"])

for path, p in zip(sys.argv[1:], probs):
    if p.max() < cfg["unknown_threshold"]:
        print(path, ["unknown"])
    else:
        print(path, [cfg["scripts"][i] for i in p.argsort(descending=True) if p[i] >= cfg["script_threshold"]])
```

## Evaluation

All test sets are strictly held out from training. Top-1 accuracy is unthresholded (before the `unknown` rule). "2 seeds" is the range over two distilled runs of this recipe (`s0` selected by `r2_val = 92.6%`; `s1` shown for spread).

| Benchmark | Label | n | Sibling `page-script-id` (MobileNetV4-S) | **This model (`page-script-id-hgnet`)** | `page-script-id-hgnet` (2 seeds) |
|---|---|---:|---:|---:|---:|
| Web PDFs (`r2_test`), text layer | text layer | 2,056 | 94.0% | **94.1%** | 94.0–94.1% |
| Web PDFs (`r2_test`), doc label | doc language | 2,695 | 94.3% | **94.4%** | 94.0–94.4% |
| Government docs (`r3_test`, 21 scripts) | text layer / scan doc | 2,140 | 86.8% | **87.6%** | 87.4–87.6% |
| β€” `r3_test` clean text-layer (`tl == doc cfg`) | text layer = doc cfg | 995 | 96.3% | **97.3%** | β€” |
| β€” `r3_test` scans subset | scan doc label | 789 | 90.1% | **90.9%** | 89.7–90.9% |
| [MDPBench](https://huggingface.co/datasets/Delores-Lin/MDPBench), digital | benchmark lang | 680 | 95.6% | **96.3%** | 96.2–96.3% |
| MDPBench, photographed | benchmark lang | 2,040 | 84.8% | **88.0%** | 88.0–88.9% |
| β€” photographed `oblique` / `hold` | benchmark lang | 239 / 286 | 64.8% / 76.9% | **69.9% / 81.5%** | 70–73% / 82–83% |
| Digital rotations `0Β° / 90Β° / 180Β° / 270Β°` | MDPBench digital | 200 | 96.0 / 90.5 / 91.5 / 91.0% | **96.0 / 91.0 / 92.0 / 91.0%** | 95.5–96 / 91–94% |
| [OmniDocBench](https://huggingface.co/datasets/samiuc/OmniDocBench-parquet), EN / ZH | human page attr | 290 / 612 | 99.7% / 91.7% | **99.3% / 93.8%** | 99.3–100% / 93.8–94.3% |
| β€” OmniDocBench `en_ch_mixed` exact set @ 0.50 | human page attr | 79 | 74.7% | **59.5%** | 59.5–70.9% |
| [Sarvam Indic OCR Bench](https://huggingface.co/datasets/sarvamai/indic-ocr-bench) crops (square-padded) | GT text script | 975 | 86.7% (`Knda` 80.4%) | **86.0%** (`Knda` **100.0%**) | 84.1–86.0% |
| Blank / zero-char old-book pages (BHL) | false positive script % | 768 | 0.00% | **0.00%** | 0.00% |

**Decision rule** (`unknown_threshold = 0.7314`, `script_threshold = 0.55`):

| Test set | n | One script (accuracy) | Two or more | Unknown |
|---|---:|---:|---:|---:|
| Web PDFs (`r2_test`, text layer) | 2,056 | 92.5% (**96.0%**) | 3.5% | 4.0% |
| Government docs (`r3_test`) | 2,140 | 85.4% (**92.5%**) | 4.3% | 10.3% |
| MDPBench, photographed | 2,040 | 68.9% (**97.6%**) | 1.8% | 29.3% |

*(Single-script spurious 2+ rate on `r2_test`: **2.2%** at `0.55`; mixed-script exact set on `r2_test` at `0.50` without gate: **47.0%**.)*

**Unseen scripts:**
- **Real 2026 Sinhala (`Sinh`) PDFs** (46 full pages from `CC-MAIN-2026-47`, never trained): **91.3%** refused as `unknown` (2 seeds: 82.6–91.3%).
- **Clean synthetic unseen (`Guru`, `Sinh`)** (NVIDIA v2 shard 00000, 160 pages): **58.8%** refused.
- **Exact 18-class leave-out** (`Geor`, `Khmr`, `Telu` removed from training, 855 `r3` pages, undistilled `hgnetb0`, 2 seeds): **45.9–49.1%** pooled refused by `max(prob)` (`Geor` 91–92%, `Khmr` 27–40%, `Telu` 14–27%; most false accepts on `Khmr` are `Latn` due to secondary Latin headings on Cambodian government PDFs, and `Telu` is confused with its visual twin `Knda`). Combining `max(prob)` with cosine similarity to pre-logit class centroids raises pooled refusal to **53.5–61.3%** (AUROC 0.903–0.906) while keeping known-script refusal under 8%. This model is **not** a reliable detector for unseen scripts.

## Speed & Parity

Measured on a cloud `a10g-large` box (12 vCPU, 1Γ— A10G), model forward only on random input (image decode adds ~15–30 ms on 1 CPU thread):

| Setup | Speed | Notes |
|---|---|---|
| ONNX Runtime FP32, 1 CPU thread, batch 1 | **78.7–79.5 ms / page** | `15.99 MB` file |
| ONNX Runtime FP32, 4 CPU threads, batch 1 | **27.9–36.0 ms / page** | |
| PyTorch (`timm`), A10G, `bf16`, batch 64 | **621 pages / sec** | |

**ONNX ↔ PyTorch parity** (400 `r2_val` pages): `max |prob diff| = 1.2e-6`, **100.0% top-1 agreement**. Post-training static INT8 quantization degraded top-1 agreement to 49.5% and was not shipped.

## Limits

1. **Unseen scripts & look-alikes:** not an unseen-script detector (Telugu held out with Kannada trained is often called Kannada; unseen scripts on pages with Latin headers often fire `Latn`).
2. **Weakest known scripts (`r3_test`):** Telugu (`62.0%`) and Gujarati (`70.7–72.4%`).
3. **Photographed Cyrillic (`ru`):** `51.7–52.5%` top-1 under heavy photographic distortion (often confused with Latin or refused as unknown).
4. **Crops:** raw squashed text-block crops are mostly refused (`35.3%` top-1); pad to a white square (`--pad`) to reach `86.0%` on real Indic crops (`100%` on Kannada).
5. **Not a "no-text" detector:** pair with a dedicated no-text classifier (e.g. `small-models-for-glam/page-ocr-flags`) when blank filtering is critical.

## Training & Attribution

- **Real PDFs:** born-digital & scanned pages from [FinePDFs](https://huggingface.co/datasets/HuggingFaceFW/finepdfs) (**ODC-By**; we thank its authors), 3,794 fresh 2026 PDFs from [Common Crawl](https://huggingface.co/commoncrawl) (`CC-MAIN-2026-47`, page-level Unicode text-layer labels), plus library/archive scans (BHL, US government docs, IDL) labelled by vision-language model agreement. No raw page images are redistributed.
- **Synthetic pages:** 8,287 purity-filtered pages from [nvidia/OCR-Synthetic-Multilingual-v2](https://huggingface.co/datasets/nvidia/OCR-Synthetic-Multilingual-v2) (**CC-BY-4.0**; positives across 21 scripts + 4 shaped negative scripts: Lao, Oriya, Meitei, Ol Chiki) and 300 Tibetan synthetic negatives from [WueNLP/Synthdog-Multilingual-100](https://huggingface.co/datasets/WueNLP/Synthdog-Multilingual-100) (**Apache-2.0**).
- **Teachers & Distillation:** 3-family ensemble of `timm/convnext_small.fb_in22k_ft_in1k_384`, `timm/hgnetv2_b4.ssld_stage2_ft_in1k`, and `timm/caformer_s36.sail_in22k_ft_in1k_384` (all Apache-2.0) distilled into `timm/hgnetv2_b0.ssld_stage2_ft_in1k` (Apache-2.0) for 14 epochs with Asymmetric Loss + soft BCE KD (`alpha=0.50, T=1.5`), oblique/curl/hand/rotation/padded-crop/CutMix augmentation, EMA weights, and `OneCycleLR`.
- **Compute:** trained on [Hugging Face Jobs](https://huggingface.co/docs/hub/jobs) (~82 min on `a10g-large` for the distilled student).