davanstrien HF Staff commited on
Commit
b9c06e5
·
verified ·
1 Parent(s): 679a186

Upload page-script-id-v2 (distilled MobileNetV4-Small 640px, FP32 ONNX + timm + card)

Browse files
Files changed (5) hide show
  1. README.md +190 -0
  2. config.json +147 -0
  3. example.py +63 -0
  4. model.onnx +3 -0
  5. model.safetensors +3 -0
README.md ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: timm
4
+ pipeline_tag: image-classification
5
+ base_model: timm/mobilenetv4_conv_small.e2400_r224_in1k
6
+ language:
7
+ - multilingual
8
+ - en
9
+ - de
10
+ - fr
11
+ - es
12
+ - pt
13
+ - it
14
+ - nl
15
+ - sv
16
+ - pl
17
+ - tr
18
+ - id
19
+ - vi
20
+ - ru
21
+ - uk
22
+ - el
23
+ - ar
24
+ - fa
25
+ - ur
26
+ - he
27
+ - hi
28
+ - bn
29
+ - gu
30
+ - ta
31
+ - te
32
+ - kn
33
+ - ml
34
+ - th
35
+ - km
36
+ - my
37
+ - ka
38
+ - hy
39
+ - am
40
+ - zh
41
+ - ja
42
+ - ko
43
+ tags:
44
+ - ocr
45
+ - script-identification
46
+ - page-classification
47
+ - document-ai
48
+ - multi-label
49
+ - onnx
50
+ - glam
51
+ - knowledge-distillation
52
+ - hf_jobs
53
+ ---
54
+
55
+ # Page script ID v2 (MobileNetV4-Small)
56
+
57
+ A fast, compact image model that looks at a document page and predicts which writing script(s) it contains, without running OCR. It outputs an independent calibrated probability for each of 21 scripts, so a page can have one script, multiple scripts (mixed-script pages), or none the model is confident about (`unknown`).
58
+
59
+ This is the **v2 drop-in replacement** for [`davanstrien/page-script-id-agent`](https://huggingface.co/davanstrien/page-script-id-agent): **identical architecture and speed** (MobileNetV4-conv-small, 2.52M parameters, 10.1 MB ONNX, **33.1 ms** on 1 CPU thread / **11.0 ms** on 4 threads, **1,773 pages/s** on an A10G in `bf16`), substantially stronger on photographed documents (**+10.1 pts** on MDPBench photographed, cutting `unknown` from 50% to 28%), Japanese & Russian pages, rotated pages, mixed-script pages, and padded text-block crops.
60
+
61
+ If you can spare ~2.4× CPU time for even higher accuracy on hard scans and photographs, see the sibling model **[`davanstrien/page-script-id-v2-hgnet`](https://huggingface.co/davanstrien/page-script-id-v2-hgnet)** (HGNetV2-B0, 3.99M parameters, 16 MB, 79 ms 1t / 36 ms 4t, 88.0% MDPBench photographed).
62
+
63
+ > **Check the thresholds on your own pages.** The default cut-offs (`0.55` for a script, `0.7038` for `unknown`) were chosen on held-out web-PDF validation pages (95% coverage). On government documents this refuses ~8% and on photographed documents ~28%. Run on a few hundred of your own pages and tune `unknown_threshold` and `script_threshold` in `config.json` before bulk routing.
64
+
65
+ **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`).
66
+
67
+ ## What changed from v1 (`page-script-id-agent`)
68
+
69
+ 1. **Fixed a Japanese multi-label bug:** in v1, 95% of born-digital Japanese training pages were labeled with *both* `Jpan=1` and `Hani=1`, causing v1 to score 47.5% top-1 on MDPBench digital Japanese. Merging Kanji (`Hani`) into `Jpan` when Kana is present raised digital `jp` to **85.0%** (and government `r3_test` `Jpan` to **100%**).
70
+ 2. **Dedicated script-only model:** v1 trained 33 heads (12 page-quality/blank heads + 21 scripts) and sliced off 12 at export. v2 trains exclusively on the 21 scripts, freeing 100% of the 2.52M trunk.
71
+ 3. **3-family teacher ensemble distillation:** trained 3 diverse heavy teachers (`convnext_small@640`, `hgnetv2_b4@640`, `caformer_s36@512`; ensemble `r2_val = 92.3%`) and distilled their clean-page soft logits into heavily augmented student inputs (strong oblique perspective warps, cylindrical page curl, edge hand occlusion, textured backgrounds, 90°/180°/270° rotations, square-padded crops, and split-page mixed-script composites).
72
+ 4. **Fresh real 2026 PDFs + cleanly shaped synthetic data:** added 3,794 real 2026 PDF pages rendered from `commoncrawl/commoncrawl` (`CC-MAIN-2026-47`) and 8,287 purity-filtered pages from `nvidia/OCR-Synthetic-Multilingual-v2` (including 4 properly shaped unseen negative scripts: Lao, Oriya, Meitei, Ol Chiki — holding out Gurmukhi and Sinhala for evaluation).
73
+
74
+ ## Quick start (ONNX Runtime)
75
+
76
+ ```bash
77
+ pip install onnxruntime pillow numpy
78
+ python example.py page.jpg
79
+ python example.py --pad crop.jpg # for wide text-block crops
80
+ python example.py --mixed page.jpg # 0.50 threshold for mixed-script search
81
+ ```
82
+
83
+ Preprocessing matters: greyscale, bilinear squash to `640 × 640`, float32 values `0..255`. ImageNet normalisation, temperature (`1.15`), and sigmoid are baked into `model.onnx`, which outputs the 21 calibrated probabilities directly.
84
+
85
+ **Tip for text-block crops:** raw squashing of wide text-block strips (`~3.5:1`) still causes most crops to return `unknown` (`~30%` top-1), **but padding the crop onto a white square before resizing (`--pad`) raises top-1 on real Indic text-block crops to 86.7%**.
86
+
87
+ ## Use with `timm`
88
+
89
+ `model.safetensors` holds the exact same weights for [timm](https://github.com/huggingface/pytorch-image-models) (`mobilenetv4_conv_small`, 21 outputs in `label_names` order). It outputs raw logits, so apply `sigmoid(logits / 1.15)` yourself.
90
+
91
+ ```python
92
+ import json
93
+ import sys
94
+ from pathlib import Path
95
+
96
+ import timm
97
+ import torch
98
+ from huggingface_hub import hf_hub_download
99
+ from PIL import Image
100
+
101
+ model_id = "hf-hub:davanstrien/page-script-id-v2"
102
+ model = timm.create_model(model_id, pretrained=True).eval()
103
+ cfg = json.loads(Path(hf_hub_download("davanstrien/page-script-id-v2", "config.json")).read_text())["inference"]
104
+ size = cfg["input_size"]
105
+ mean = torch.tensor(model.pretrained_cfg["mean"]).view(3, 1, 1)
106
+ std = torch.tensor(model.pretrained_cfg["std"]).view(3, 1, 1)
107
+
108
+
109
+ def load_page(path):
110
+ im = Image.open(path)
111
+ if im.format == "JPEG":
112
+ im.draft("L", (2 * size, 2 * size))
113
+ grey = im.convert("L").resize((size, size), Image.BILINEAR)
114
+ x = torch.frombuffer(bytearray(grey.tobytes()), dtype=torch.uint8).float().view(1, size, size) / 255
115
+ return (x.expand(3, -1, -1) - mean) / std
116
+
117
+
118
+ with torch.inference_mode():
119
+ x = torch.stack([load_page(p) for p in sys.argv[1:]])
120
+ probs = torch.sigmoid(model(x) / cfg["temperature"])
121
+
122
+ for path, p in zip(sys.argv[1:], probs):
123
+ if p.max() < cfg["unknown_threshold"]:
124
+ print(path, ["unknown"])
125
+ else:
126
+ print(path, [cfg["scripts"][i] for i in p.argsort(descending=True) if p[i] >= cfg["script_threshold"]])
127
+ ```
128
+
129
+ ## Evaluation
130
+
131
+ All test benchmarks are strictly held out from training (never trained on test documents, MDPBench, OmniDocBench, Sarvam Indic OCR Bench, or held-out unseen scripts Gurmukhi/Sinhala). 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`; `s1` shown for spread).
132
+
133
+ | Benchmark | Label | n | v1 (`page-script-id-agent`) | **This model (v2)** | v2 (2 seeds) | Sibling `v2-hgnet` |
134
+ |---|---|---:|---:|---:|---:|---:|
135
+ | Web PDFs (`r2_test`), text layer | text layer | 2,056 | 92.1% | **94.0%** | 93.9–94.0% | 94.1% |
136
+ | Web PDFs (`r2_test`), doc label | doc language | 2,695 | 90.7% | **94.3%** | 93.5–94.3% | 94.4% |
137
+ | Government docs (`r3_test`, 21 scripts) | text layer / scan doc | 2,140 | 86.3% | **86.8%** | 86.8–86.9% | 87.6% |
138
+ | — `r3_test` scans subset | scan doc label | 789 | 87.0% | **90.1%** | 89.1–90.1% | 90.9% |
139
+ | [MDPBench](https://huggingface.co/datasets/Delores-Lin/MDPBench), digital | benchmark lang | 680 | 90.3% | **95.6%** | 94.7–95.6% | 96.3% |
140
+ | — digital Japanese (`jp`) / Russian (`ru`) | benchmark lang | 40 / 40 | 47.5% / 70.0% | **85.0% / 90.0%** | 85–88% / 80–90% | 82.5% / 82.5% |
141
+ | MDPBench, photographed | benchmark lang | 2,040 | 74.7% | **84.8%** | 84.8–85.6% | 88.0% |
142
+ | — photographed `oblique` / `hold` | benchmark lang | 239 / 286 | 47.7% / 59.8% | **64.8% / 76.9%** | 65–66% / 77% | 69.9% / 81.5% |
143
+ | Digital rotations `0° / 90° / 180° / 270°` | MDPBench digital | 200 | 90.5 / 79.5 / 82.5 / 81.5% | **96.0 / 90.5 / 91.5 / 91.0%** | 95.5–96 / 90–91% | 96.0 / 91.0 / 92.0 / 91.0% |
144
+ | [OmniDocBench](https://huggingface.co/datasets/samiuc/OmniDocBench-parquet), EN / ZH | human page attr | 290 / 612 | 98.3% / 92.5% | **99.7% / 91.7%** | 99.7–100% / 91.5–91.7% | 99.3% / 93.8% |
145
+ | — OmniDocBench `en_ch_mixed` exact set @ 0.50 | human page attr | 79 | 12.7% | **74.7%** | 69.6–74.7% | 59.5% |
146
+ | — OmniDocBench handwritten `note` | human page attr | 116 | 94.0% | **94.0%** | 94.0–97.4% | 91.4% |
147
+ | [Sarvam Indic OCR Bench](https://huggingface.co/datasets/sarvamai/indic-ocr-bench) crops (square-padded) | GT text script | 975 | 76.2% (`Knda` 8.7%) | **86.7%** (`Knda` **80.4%**) | 84.4–86.7% | 86.0% (`Knda` **100%**) |
148
+ | Blank / zero-char old-book pages (BHL) | false positive script % | 768 | 0.26% | **0.00%** | 0.00% | 0.00% |
149
+
150
+ **Decision rule** (`unknown_threshold = 0.7038`, `script_threshold = 0.55`):
151
+
152
+ | Test set | n | One script (accuracy) | Two or more | Unknown |
153
+ |---|---:|---:|---:|---:|
154
+ | Web PDFs (`r2_test`, text layer) | 2,056 | 92.4% (**95.7%**) | 3.1% | 4.5% |
155
+ | Government docs (`r3_test`) | 2,140 | 87.9% (**91.2%**) | 4.1% | 8.0% |
156
+ | MDPBench, photographed | 2,040 | 70.3% (**93.7%**) | 2.0% | 27.7% |
157
+
158
+ *(Single-script spurious 2+ rate on `r2_test`: **2.1%** at `0.55`; mixed-script exact set on `r2_test` at `0.50` without gate: **46.6%** vs v1's 34.2%.)*
159
+
160
+ **Unseen scripts:**
161
+ - **Real 2026 Sinhala (`Sinh`) PDFs** (46 full pages from `CC-MAIN-2026-47`, never trained): **73.9%** refused as `unknown` (2 seeds: 73.9–78.3%; v1: 54.4%).
162
+ - **Clean synthetic unseen (`Guru`, `Sinh`)** (NVIDIA v2 shard 00000, 160 pages): **51.9%** refused (v1: 44.4%).
163
+ - **Exact 18-class leave-out** (`Geor`, `Khmr`, `Telu` removed from training, 855 `r3` pages, undistilled v2 `mnv4s`): **61.6%** pooled refused (`Geor` 91.9%, `Telu` 59.5%, `Khmr` 44.6%). On real `r3` `Khmr` pages that also contain secondary Latin headers/URLs, stronger multi-label Latin sensitivity fires `Latn` rather than `unknown`. As in v1, this model is **not** a reliable detector for unseen scripts.
164
+
165
+ ## Speed & Parity
166
+
167
+ 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):
168
+
169
+ | Setup | Speed | Notes |
170
+ |---|---|---|
171
+ | ONNX Runtime FP32, 1 CPU thread, batch 1 | **33.1–34.3 ms / page** | `10.06 MB` file |
172
+ | ONNX Runtime FP32, 4 CPU threads, batch 1 | **11.0–13.2 ms / page** | |
173
+ | PyTorch (`timm`), A10G, `bf16`, batch 64 | **1,773 pages / sec** | |
174
+
175
+ **ONNX ↔ PyTorch parity** (400 `r2_val` pages): `max |prob diff| = 2.0e-6`, **100.0% top-1 agreement**. Post-training INT8 quantization (both static QDQ and dynamic) was tested and **not shipped**: on MobileNetV4 depthwise convolutions, PTQ degraded agreement to 63.8% (static) / 6.5% (dynamic) without improving 1-thread CPU latency.
176
+
177
+ ## Limits
178
+
179
+ 1. **Unseen scripts & look-alikes:** not an unseen-script detector. Unseen scripts that visually resemble trained scripts (e.g. Gurmukhi → Devanagari, Sinhala → Kannada/Telugu) or appear alongside secondary Latin headers are often accepted with moderate-to-high confidence.
180
+ 2. **Weakest known scripts (`r3_test`):** Telugu (`60.0%`, 2 seeds 60–62%) and Gujarati (`72.4%`) remain the weakest classes.
181
+ 3. **Photographed Cyrillic (`ru`):** while digital `ru` jumped to 90.0%, severely degraded photographed `ru` is still `52.5%` top-1 (often confused with Latin or refused as unknown).
182
+ 4. **Crops:** raw squashed text-block crops are still mostly refused (`~30%` top-1). Use square white padding (`--pad`) if running on crops.
183
+ 5. **Not a "no-text" detector:** although blank BHL old-book pages had `0.00%` false positives here, pair with a dedicated no-text classifier (e.g. `small-models-for-glam/page-ocr-flags`) if blank detection is critical.
184
+
185
+ ## Training & Attribution
186
+
187
+ - **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.
188
+ - **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**).
189
+ - **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/mobilenetv4_conv_small.e2400_r224_in1k` (Apache-2.0) for 16 epochs with Asymmetric Loss + soft BCE KD (`alpha=0.50, T=1.5`), EMA weights, and `OneCycleLR`.
190
+ - **Compute:** trained on [Hugging Face Jobs](https://huggingface.co/docs/hub/jobs) (~52 min on `a10g-small` for the distilled student).
config.json ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architecture": "mobilenetv4_conv_small",
3
+ "num_classes": 21,
4
+ "label_names": [
5
+ "Arab",
6
+ "Beng",
7
+ "Cyrl",
8
+ "Deva",
9
+ "Grek",
10
+ "Hang",
11
+ "Hani",
12
+ "Hebr",
13
+ "Jpan",
14
+ "Latn",
15
+ "Taml",
16
+ "Thai",
17
+ "Armn",
18
+ "Ethi",
19
+ "Geor",
20
+ "Gujr",
21
+ "Khmr",
22
+ "Knda",
23
+ "Mlym",
24
+ "Mymr",
25
+ "Telu"
26
+ ],
27
+ "model_args": {
28
+ "num_classes": 21,
29
+ "in_chans": 3
30
+ },
31
+ "pretrained_cfg": {
32
+ "custom_load": false,
33
+ "input_size": [
34
+ 3,
35
+ 640,
36
+ 640
37
+ ],
38
+ "test_input_size": [
39
+ 3,
40
+ 640,
41
+ 640
42
+ ],
43
+ "fixed_input_size": false,
44
+ "interpolation": "bilinear",
45
+ "crop_pct": 1.0,
46
+ "test_crop_pct": 1.0,
47
+ "crop_mode": "squash",
48
+ "mean": [
49
+ 0.485,
50
+ 0.456,
51
+ 0.406
52
+ ],
53
+ "std": [
54
+ 0.229,
55
+ 0.224,
56
+ 0.225
57
+ ],
58
+ "num_classes": 21,
59
+ "license": "apache-2.0",
60
+ "label_names": [
61
+ "Arab",
62
+ "Beng",
63
+ "Cyrl",
64
+ "Deva",
65
+ "Grek",
66
+ "Hang",
67
+ "Hani",
68
+ "Hebr",
69
+ "Jpan",
70
+ "Latn",
71
+ "Taml",
72
+ "Thai",
73
+ "Armn",
74
+ "Ethi",
75
+ "Geor",
76
+ "Gujr",
77
+ "Khmr",
78
+ "Knda",
79
+ "Mlym",
80
+ "Mymr",
81
+ "Telu"
82
+ ]
83
+ },
84
+ "inference": {
85
+ "onnx_file": "model.onnx",
86
+ "onnx_input_name": "grey",
87
+ "onnx_output_name": "probabilities",
88
+ "input_size": 640,
89
+ "temperature": 1.15,
90
+ "scripts": [
91
+ "Arab",
92
+ "Beng",
93
+ "Cyrl",
94
+ "Deva",
95
+ "Grek",
96
+ "Hang",
97
+ "Hani",
98
+ "Hebr",
99
+ "Jpan",
100
+ "Latn",
101
+ "Taml",
102
+ "Thai",
103
+ "Armn",
104
+ "Ethi",
105
+ "Geor",
106
+ "Gujr",
107
+ "Khmr",
108
+ "Knda",
109
+ "Mlym",
110
+ "Mymr",
111
+ "Telu"
112
+ ],
113
+ "script_names": {
114
+ "Arab": "Arabic",
115
+ "Beng": "Bengali",
116
+ "Cyrl": "Cyrillic",
117
+ "Deva": "Devanagari",
118
+ "Grek": "Greek",
119
+ "Hang": "Hangul",
120
+ "Hani": "Han",
121
+ "Hebr": "Hebrew",
122
+ "Jpan": "Japanese",
123
+ "Latn": "Latin",
124
+ "Taml": "Tamil",
125
+ "Thai": "Thai",
126
+ "Armn": "Armenian",
127
+ "Ethi": "Ethiopic",
128
+ "Geor": "Georgian",
129
+ "Gujr": "Gujarati",
130
+ "Khmr": "Khmer",
131
+ "Knda": "Kannada",
132
+ "Mlym": "Malayalam",
133
+ "Mymr": "Myanmar",
134
+ "Telu": "Telugu"
135
+ },
136
+ "unknown_threshold": 0.7038,
137
+ "script_threshold": 0.55,
138
+ "mixed_page_threshold": 0.5,
139
+ "colour": "greyscale page",
140
+ "resize": "bilinear squash to 640 x 640 (aspect ratio not kept, no crop, no padding); for wide text-block crops, pad to a white square before resizing",
141
+ "jpeg_draft": "for JPEG input, decode at reduced scale with PIL draft(L, (1280, 1280)) before the resize, as in training",
142
+ "onnx_input": "float32, N x 640 x 640, grey values 0 to 255; normalisation, temperature and sigmoid are inside the ONNX graph; output N x 21 probabilities",
143
+ "timm_input": "float32, N x 3 x 640 x 640: grey / 255 copied to three channels, then (x - mean) / std with the pretrained_cfg mean and std; output N x 21 logits",
144
+ "probability": "timm: sigmoid(logit / 1.15) per script (the ONNX file already returns this)",
145
+ "rule": "if the largest probability is below unknown_threshold, the page is unknown; otherwise report every script with probability >= script_threshold (or mixed_page_threshold=0.50 when finding mixed-script pages matters more than a clean single answer)."
146
+ }
147
+ }
example.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Page script identification with ONNX Runtime.
2
+
3
+ Usage:
4
+ python example.py page.jpg [more pages ...]
5
+ python example.py --pad crop.jpg # for wide text-block crops
6
+ python example.py --mixed page.jpg # lower second-script threshold (0.50)
7
+
8
+ Needs: pip install onnxruntime pillow numpy
9
+ """
10
+ import argparse
11
+ import json
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import onnxruntime as ort
16
+ from PIL import Image
17
+
18
+ HERE = Path(__file__).parent
19
+ CFG = json.loads((HERE / "config.json").read_text())["inference"]
20
+ SESSION = ort.InferenceSession(str(HERE / CFG["onnx_file"]), providers=["CPUExecutionProvider"])
21
+
22
+
23
+ def load_page(path, pad_square=False):
24
+ size = CFG["input_size"]
25
+ im = Image.open(path)
26
+ if im.format == "JPEG" and not pad_square:
27
+ im.draft("L", (2 * size, 2 * size)) # faster JPEG decode, as in training
28
+ grey = im.convert("L")
29
+ if pad_square:
30
+ w, h = grey.size
31
+ s = max(w, h)
32
+ canvas = Image.new("L", (s, s), 255)
33
+ canvas.paste(grey, ((s - w) // 2, (s - h) // 2))
34
+ grey = canvas
35
+ grey = grey.resize((size, size), Image.BILINEAR)
36
+ return np.asarray(grey, np.float32)[None] # 0..255; norm + temp + sigmoid are inside ONNX
37
+
38
+
39
+ def script_probs(path, pad_square=False):
40
+ probs = SESSION.run([CFG["onnx_output_name"]], {CFG["onnx_input_name"]: load_page(path, pad_square=pad_square)})[0][0]
41
+ return dict(zip(CFG["scripts"], probs.tolist()))
42
+
43
+
44
+ def decide(probs, threshold=CFG["script_threshold"], unknown_threshold=CFG["unknown_threshold"]):
45
+ if max(probs.values()) < unknown_threshold:
46
+ return ["unknown"]
47
+ found = [s for s, p in probs.items() if p >= threshold]
48
+ if not found:
49
+ found = [max(probs, key=probs.get)]
50
+ return sorted(found, key=lambda s: -probs[s])
51
+
52
+
53
+ if __name__ == "__main__":
54
+ ap = argparse.ArgumentParser()
55
+ ap.add_argument("paths", nargs="+")
56
+ ap.add_argument("--pad", action="store_true", help="Pad image to a white square (recommended for text-block crops)")
57
+ ap.add_argument("--mixed", action="store_true", help="Use mixed_page_threshold (0.50) instead of 0.55")
58
+ args = ap.parse_args()
59
+ thr = CFG["mixed_page_threshold"] if args.mixed else CFG["script_threshold"]
60
+ for path in args.paths:
61
+ probs = script_probs(path, pad_square=args.pad)
62
+ top = sorted(probs.items(), key=lambda kv: -kv[1])[:3]
63
+ print(path, decide(probs, threshold=thr), {s: round(p, 3) for s, p in top})
model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d713c043dc709c08f319f9d67cb1a7ed00b33889699e7b38329d315e8c07c76
3
+ size 10055428
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ea6098def58e4a5773739997f014a73220a0077002d18be2caa011fdedc2f32
3
+ size 10206612