Image Classification
timm
ONNX
Safetensors
ocr
script-identification
page-classification
document-ai
multi-label
glam
knowledge-distillation
hf_jobs
Instructions to use davanstrien/page-script-id with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- timm
How to use davanstrien/page-script-id with timm:
import timm model = timm.create_model("hf-hub:davanstrien/page-script-id", pretrained=True) - Notebooks
- Google Colab
- Kaggle
|
Download README.md from davanstrien/page-script-id: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/davanstrien/page-script-id/resolve/main/README.md
- Command line
-
hf download hf://davanstrien/page-script-id/README.md
-
curl -L -o README.md https://huggingface.co/davanstrien/page-script-id/resolve/main/README.md
12.7 kB
| license: apache-2.0 | |
| library_name: timm | |
| pipeline_tag: image-classification | |
| base_model: timm/mobilenetv4_conv_small.e2400_r224_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 (MobileNetV4-Small) | |
| A fast, compact image model that looks at a document page and predicts which writing script(s) it contains, without running OCR. It returns 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`). Use it to route pages to the right OCR model or language pack, sort large collections by script, or flag pages whose script does not match their metadata. | |
| Built on **MobileNetV4-conv-small** (2.52M parameters, 10.1 MB as ONNX or `timm` weights), distilled from a 3-family teacher ensemble (`convnext_small`, `hgnetv2_b4`, `caformer_s36`) on [Hugging Face Jobs](https://huggingface.co/docs/hub/jobs). Takes a greyscale page squashed to `640 Γ 640` and runs in **33 ms** on 1 CPU thread, **11 ms** on 4 threads, or **1,773 pages/s** on an A10G (`bf16`, batch 64). | |
| - **Try it live:** [Page Script ID Demo Space](https://huggingface.co/spaces/davanstrien/page-script-id-demo) (runs on free CPU β upload images or PDFs, toggle crop padding, tune thresholds live) | |
| - **Higher-accuracy sibling:** [`davanstrien/page-script-id-hgnet`](https://huggingface.co/davanstrien/page-script-id-hgnet) (HGNetV2-B0, 3.99M parameters, 16 MB, 79 ms 1t / 36 ms 4t, 88.0% MDPBench photographed) | |
| > **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. | |
| **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 matters: greyscale, bilinear squash to `640 Γ 640`, float32 values `0..255`. ImageNet normalisation, temperature (`1.15`), and sigmoid are baked into `model.onnx`, which returns the 21 calibrated probabilities directly. | |
| **Tip for text-block crops:** raw squashing of wide text-block strips (`~3.5:1`) 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%**. | |
| ## Use with `timm` | |
| `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 returns raw logits, so apply `sigmoid(logits / 1.15)` yourself. | |
| ```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" | |
| model = timm.create_model(model_id, pretrained=True).eval() | |
| cfg = json.loads(Path(hf_hub_download("davanstrien/page-script-id", "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 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). | |
| | Benchmark | Label | n | **This model** | 2 seeds | Sibling `page-script-id-hgnet` | | |
| |---|---|---:|---:|---:|---:| | |
| | Web PDFs (`r2_test`), text layer | text layer | 2,056 | **94.0%** | 93.9β94.0% | 94.1% | | |
| | Web PDFs (`r2_test`), doc label | doc language | 2,695 | **94.3%** | 93.5β94.3% | 94.4% | | |
| | Government docs (`r3_test`, 21 scripts) | text layer / scan doc | 2,140 | **86.8%** | 86.8β86.9% | 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%** | 89.1β90.1% | 90.9% | | |
| | [MDPBench](https://huggingface.co/datasets/Delores-Lin/MDPBench), digital | benchmark lang | 680 | **95.6%** | 94.7β95.6% | 96.3% | | |
| | β digital Japanese (`jp`) / Russian (`ru`) | benchmark lang | 40 / 40 | **85.0% / 90.0%** | 85β88% / 80β90% | 82.5% / 82.5% | | |
| | MDPBench, photographed | benchmark lang | 2,040 | **84.8%** | 84.8β85.6% | 88.0% | | |
| | β photographed `oblique` / `hold` | benchmark lang | 239 / 286 | **64.8% / 76.9%** | 65β66% / 77% | 69.9% / 81.5% | | |
| | Digital rotations `0Β° / 90Β° / 180Β° / 270Β°` | MDPBench digital | 200 | **96.0 / 90.5 / 91.5 / 91.0%** | 95.5β96 / 90β91% | 96.0 / 91.0 / 92.0 / 91.0% | | |
| | [OmniDocBench](https://huggingface.co/datasets/samiuc/OmniDocBench-parquet), EN / ZH | human page attr | 290 / 612 | **99.7% / 91.7%** | 99.7β100% / 91.5β91.7% | 99.3% / 93.8% | | |
| | β OmniDocBench `en_ch_mixed` exact set @ 0.50 | human page attr | 79 | **74.7%** | 69.6β74.7% | 59.5% | | |
| | β OmniDocBench handwritten `note` | human page attr | 116 | **94.0%** | 94.0β97.4% | 91.4% | | |
| | [Sarvam Indic OCR Bench](https://huggingface.co/datasets/sarvamai/indic-ocr-bench) crops (square-padded) | GT text script | 975 | **86.7%** (`Knda` **80.4%**) | 84.4β86.7% | 86.0% (`Knda` **100%**) | | |
| | Blank / zero-char old-book pages (BHL) | false positive script % | 768 | **0.00%** | 0.00% | 0.00% | | |
| **Decision rule** (`unknown_threshold = 0.7038`, `script_threshold = 0.55`): | |
| | Test set | n | One script (accuracy) | Two or more | Unknown | | |
| |---|---:|---:|---:|---:| | |
| | Web PDFs (`r2_test`, text layer) | 2,056 | 92.4% (**95.7%**) | 3.1% | 4.5% | | |
| | Government docs (`r3_test`) | 2,140 | 87.9% (**91.2%**) | 4.1% | 8.0% | | |
| | MDPBench, photographed | 2,040 | 70.3% (**93.7%**) | 2.0% | 27.7% | | |
| *(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%**.)* | |
| **Unseen scripts:** | |
| - **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%). | |
| - **Clean synthetic unseen (`Guru`, `Sinh`)** (NVIDIA v2 shard 00000, 160 pages): **51.9%** refused. | |
| - **Exact 18-class leave-out** (`Geor`, `Khmr`, `Telu` removed from training, 855 `r3` pages, undistilled `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, multi-label Latin sensitivity fires `Latn` rather than `unknown`. 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 | **33.1β34.3 ms / page** | `10.06 MB` file | | |
| | ONNX Runtime FP32, 4 CPU threads, batch 1 | **11.0β13.2 ms / page** | | | |
| | PyTorch (`timm`), A10G, `bf16`, batch 64 | **1,773 pages / sec** | | | |
| **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. | |
| ## Bulk curation receipt (Common Crawl `CC-MAIN-2026-47`) | |
| Run end-to-end on a single **pure-CPU** Hugging Face Job (`cpu-xl`, 16 vCPU, `$1.00/hr`, zero GPU) directly against `hf://buckets/commoncrawl/commoncrawl`: | |
| - **21,490 pages** across **13,308 real November 2026 web PDFs** (9,335 unique hosts, 30 TLDs) in **10.5 minutes** for **$0.175** (`35.6 pages/s` end-to-end including WARC byte-range fetch, gzip decompress, PyMuPDF text extract + render, and ONNX inference). | |
| - **98.7%** agreement with PDF text-layer Unicode script counts on answered born-digital pages (`97.9%` unthresholded). | |
| - **13.4%** of pages (`2,883`) had no usable text layer (`<30` letters); visual routing immediately assigned a script to **74.5%** (`2,147`) across 15+ scripts and refused the remaining `736` blank/chart/unknown pages. | |
| - Flagged **119 pages** whose text layer contained `β₯60` Latin characters (broken legacy font CMaps or wrong-language OCR) where the vision model identified the true non-Latin script at `β₯0.85` confidence (e.g. Cyrillic `0.978`, Armenian `0.995`), plus **276 mixed-script pages** (`1.3%`). | |
| ## Limits | |
| 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. | |
| 2. **Weakest known scripts (`r3_test`):** Telugu (`60.0%`, 2 seeds 60β62%) and Gujarati (`72.4%`) remain the weakest classes. | |
| 3. **Photographed Cyrillic (`ru`):** while digital `ru` reaches 90.0%, severely degraded photographed `ru` is `52.5%` top-1 (often confused with Latin or refused as unknown). | |
| 4. **Crops:** raw squashed text-block crops are mostly refused (`~30%` top-1). Use square white padding (`--pad`) if running on crops. | |
| 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. | |
| ## 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/mobilenetv4_conv_small.e2400_r224_in1k` (Apache-2.0) for 16 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) (~52 min on `a10g-small` for the distilled student). | |