davanstrien's picture
davanstrien HF Staff
Card: remove the draft review block
5b7a247 verified
|
Raw History Blame Contribute Delete
14.8 kB
metadata
license: apache-2.0
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
library_name: timm
pipeline_tag: image-classification
base_model: timm/mobilenetv4_conv_small.e2400_r224_in1k
tags:
  - ocr
  - script-identification
  - page-classification
  - document-ai
  - multi-label
  - onnx
  - glam
  - hf_jobs

Page script ID

A small image model that looks at a whole document page and says which writing script it is in, without running OCR. It returns an independent probability for each of 21 scripts, so a page can have two scripts, or none the model is sure of ("unknown"). Use it to route pages to the right OCR model or language pack, to sort a large collection by script, or to find pages whose script does not match their metadata.

MobileNetV4-conv-small, 2.5M parameters, 10 MB as ONNX or as timm weights. Greyscale page squashed to 640 Γ— 640. 33 ms per page on one CPU thread, 12 ms on four (model only).

Trained on Hugging Face Jobs: one A10G, about 23 minutes per run. Details are under Training.

Check the thresholds on your own pages. The default cut-offs (0.55 for a script, 0.627 for "unknown") were chosen on web PDFs and do not carry over unchanged. The same rule returns "unknown" for 5% of web-PDF pages, 11.5% of government documents and half of photographed pages. Before you filter or route on the decision, run the model on a few hundred of your own pages, look at the probabilities, and set the cut-offs there.

Scripts: Arabic, Armenian, Bengali, Cyrillic, Devanagari, Ethiopic, Georgian, Greek, Gujarati, Han, Hangul, Hebrew, Japanese, Kannada, Khmer, Latin, Malayalam, Myanmar, Tamil, Telugu, Thai.

Quick start

pip install onnxruntime pillow numpy
python example.py page.jpg

It prints the decision (a list of scripts, or unknown) and the three highest probabilities. example.py reads its settings from the inference section of config.json (the rest of that file is the timm configuration):

import json
import sys
from pathlib import Path

import numpy as np
import onnxruntime as ort
from PIL import Image

HERE = Path(__file__).parent
CFG = json.loads((HERE / "config.json").read_text())["inference"]  # our settings; the rest is for timm
SESSION = ort.InferenceSession(str(HERE / CFG["onnx_file"]), providers=["CPUExecutionProvider"])


def load_page(path):
    size = CFG["input_size"]
    im = Image.open(path)
    if im.format == "JPEG":
        im.draft("L", (2 * size, 2 * size))  # faster JPEG decode, as in training
    grey = im.convert("L").resize((size, size), Image.BILINEAR)  # squash, no crop
    return np.asarray(grey, np.float32)[None]  # 0..255; everything else is inside the model


def script_probs(path):
    probs = SESSION.run([CFG["onnx_output_name"]], {CFG["onnx_input_name"]: load_page(path)})[0][0]
    return dict(zip(CFG["scripts"], probs.tolist()))


def decide(probs, threshold=CFG["script_threshold"]):
    if max(probs.values()) < CFG["unknown_threshold"]:
        return ["unknown"]
    found = [s for s, p in probs.items() if p >= threshold]
    return sorted(found, key=lambda s: -probs[s])


if __name__ == "__main__":
    for path in sys.argv[1:]:
        probs = script_probs(path)
        top = sorted(probs.items(), key=lambda kv: -kv[1])[:3]
        print(path, decide(probs), {s: round(p, 3) for s, p in top})

Preprocessing matters: grey, bilinear squash to 640 Γ— 640 (no crop, no padding), values 0 to 255. Normalisation, the temperature (2.3) and the sigmoid are inside the model, which returns the 21 probabilities directly.

Use with timm

model.safetensors holds the same weights for timm: mobilenetv4_conv_small with exactly the 21 script outputs, in the order of label_names. It returns logits, with no temperature or sigmoid inside, so apply sigmoid(logits / 2.3) yourself. Its input is three channels: the grey page divided by 255, copied to all three channels, then normalised with the ImageNet mean and std in pretrained_cfg, exactly as in training. Needs pip install timm pillow.

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 = sys.argv[1]  # "hf-hub:<namespace>/page-script-id" or "local-dir:/path/to/folder"
model = timm.create_model(model_id, pretrained=True).eval()
src, name = model_id.split(":", 1)
cfg_file = Path(name) / "config.json" if src == "local-dir" else hf_hub_download(name, "config.json")
INF = json.loads(Path(cfg_file).read_text())["inference"]
size = model.pretrained_cfg["input_size"][-1]
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)  # grey, squash, no crop
    x = torch.frombuffer(bytearray(grey.tobytes()), dtype=torch.uint8).float().view(1, size, size) / 255
    return (x.expand(3, -1, -1) - mean) / std  # grey copied to 3 channels, ImageNet mean/std


pages = sys.argv[2:]
with torch.inference_mode():
    probs = torch.sigmoid(model(torch.stack([load_page(p) for p in pages])) / INF["temperature"])
for path, p in zip(pages, probs):
    if p.max() < INF["unknown_threshold"]:
        print(path, ["unknown"])
    else:
        print(path, [INF["scripts"][i] for i in p.argsort(descending=True) if p[i] >= INF["script_threshold"]])

Run it as python run_timm.py hf-hub:<namespace>/page-script-id page.jpg or with local-dir:/path/to/folder. Prefer the ONNX file for CPU pipelines and when you do not want a PyTorch dependency; prefer timm for GPU batches and for fine-tuning.

How to read the output

  • Unknown: the largest probability is below 0.627: an unfamiliar script, not a normal text page, or too hard. Expect this on about 5% of ordinary pages.
  • One script: one probability at or above the script threshold (0.55).
  • Several scripts: two or more at or above it, usually a mixed page.
  • No text: not an output of this model. Blank pages usually come out "unknown", but not always. Take "no text" from a separate no-text model, such as the no_text output of page-ocr-flags.

0.627 is the value at which 95% of 2,071 validation pages are still answered; the temperature was fitted on the same pages. Both thresholds are in the inference section of config.json: change them there once you have checked them on your own pages.

Why 0.55 for the script threshold. It is the value chosen on the validation pages for this checkpoint. A lower value finds more mixed pages but gives more single-script pages a spurious second script. Computed for this card from the saved predictions on the 2,056 web-PDF test pages (unknown 5.3% in both cases):

Script threshold Two or more scripts Single-script pages given two Mixed pages (247): exact set Mixed pages: at least one right
0.55 (default) 5.8% 1.8% 29.1% 86.2%
0.5 7.8% 3.0% 36.0% 86.6%

Lower it to 0.5 (mixed_page_threshold in config.json) when you are searching for mixed pages and finding them matters more than a clean single answer.

What it is for, and what it is not for

For full pages of documents: born-digital PDFs, office and library scans. Before you rely on it:

  • Full pages only. On cropped text blocks it is unreliable and refuses most of them, whatever their script.
  • Weak on photographs. On photographed documents it is right on 75% of pages, and the rule returns "unknown" for about half of them.
  • Related scripts are confused. A page in a script the model was not trained on, but which looks like one it was (Telugu next to Kannada), is often given the look-alike with confidence.
  • About two thirds of pages in an unseen script are returned as unknown. The rest usually get one wrong script with moderate confidence. It is not a detector for unseen scripts.

Evaluation

All test pages come from documents never used in training. Labels are automatic, not human: the script counted from the PDF's own text layer, the language of the document, or agreement between vision-language models. Accuracy is the top script against the label on every page, before the unknown rule. "3 seeds" is the range over three training runs of the same recipe; this file is one of them.

Test pages Label n This model 3 seeds
Held-out pages of web PDFs, 25 languages document language (wrong for about 6% of pages) 2,695 92.2% 91.6–92.2%
The same pages where the text layer is usable script of the text layer 2,056 92.2% 91.7–92.2%
Held-out government documents, 21 scripts text layer; document language for scans 2,140 86.1% 85.7–86.1%
MDPBench, digital renders benchmark language 680 90.4% 88.8–90.4%
MDPBench, photographed benchmark language 2,040 74.8% 74.8–77.4%
Hard pages: blackletter, rotated, non-Latin in old books four models agreed (unanimous) 113 91.2% 90.3–92.9%

Against other ways of getting the script, on the same 2,695 web-PDF pages and document-language label:

Method Accuracy Cost
This model 92.2% 33 ms per page, one CPU thread
Script of the text from a full OCR pass (Indra OCR 1.2) 96.4% about 2.4 s per page per CPU core
Tesseract OSD 55.0% about 1.8 s per page
PaddleClas PULC language_classification, vote over detected text lines 34.9% used as documented; 65.9% with lines cut into word-shaped windows needs a text detector first; no Hebrew, Greek, Bengali or Thai class

If you run full OCR anyway, its text gives a better script label; this model is for the step before OCR. The PULC windowing variant is our own adaptation, chosen after looking at 80 pages.

The decision rule (thresholds 0.627 and 0.55):

Test pages n One script (accuracy) Two or more Unknown
Web PDFs, text-layer label 2,056 89.0% (95.0%) 5.8% 5.2%
Government documents 2,140 83.6% (91.9%) 4.9% 11.5%
MDPBench, photographed 2,040 48.6% (91.8%) 1.9% 49.5%

Mixed pages (two or more scripts in the text layer; 247 web-PDF and 185 government pages): reporting every script at 0.5 without the unknown rule, the exact set is returned on 36% and 40%, and at least one right script on 93% and 89%.

Blank pages: of 1,048 held-out old-book pages with no OCR text, 1.9% are given a script.

Unseen scripts. The recipe was re-run twice with Georgian, Khmer and Telugu removed from training, then tested on 855 pages in those scripts:

Outcome for a page in an unseen script Run 1 Run 2
Returned as unknown 68% 67%
One wrong script (mostly Latin, Thai or Kannada, at about 0.75) 26% 28%
Two scripts 6% 5%

By script: Georgian refused on 88–90% of pages, Khmer 61–65%, Telugu 47–54%.

Limits and failure modes

  1. Look-alike scripts. Held out, Telugu is refused on only about half of pages and otherwise called Kannada or Latin, with confidence. In an earlier study, Malayalam held out with Tamil trained was refused on 40%.
  2. Not supported: scene text, handwriting, crops.
  3. Weakest known scripts (government pages): Telugu about 0.6 and Gujarati about 0.7, both with thin training data; Japanese as low as 0.53, on only 17 pages.
  4. Script of the dominant text. Short Latin numbering or captions on a non-Latin page may or may not appear as a second script.
  5. Optimistic numbers. Most test pages come from the same collections as the training pages. Expect lower accuracy and more "unknown" elsewhere.
  6. Weak labels. Evaluation labels come from text layers, document metadata and model agreement. There is almost no human-labelled test data.
  7. Synthetic unseen script. Synthetic pages in a script held back from training (Gurmukhi) were refused on only 32% by this checkpoint.

Speed

Model forward pass only, on random input, on a 48-vCPU cloud machine with one A10G. Decoding the page image is extra: about 15–30 ms per page on one thread.

Setup Time
ONNX Runtime, 1 CPU thread, batch 1 33.3 ms per page
ONNX Runtime, 4 CPU threads, batch 1 11.8 ms per page
PyTorch (the model.safetensors network), A10G, bf16, batch 64 1,771 pages per second

CPU times were measured on an earlier export of the same network with the normalisation and temperature outside the graph. model.onnx and model.safetensors give the same probabilities (largest difference 1.7e-6 on 400 test pages, the same decision on every page).

Training

  • Born-digital pages rendered from web PDFs in the FinePDFs dataset (ODC-By; we acknowledge and thank its authors). Labels: script counts from the PDF text layer (every script with at least 30 letters and a 10% share, so a page can have two). Scanned pages from the same documents use the document language, at reduced weight.
  • Library and archive scans (Biodiversity Heritage Library, US government documents, Industry Documents Library, Library of Congress), labelled by two vision-language models where they agreed.
  • Negatives: pages in scripts without a class (real Tibetan pages; synthetic Tibetan and Lao pages from Synthdog-Multilingual-100), with every output at zero; this teaches "unknown". As many synthetic pages in trained scripts stop it learning "synthetic means unknown".
  • Recipe: MobileNetV4-conv-small from ImageNet weights, greyscale pages squashed to 640 Γ— 640, one sigmoid per script, class-balanced sampling, 8 epochs. One temperature, fitted on validation pages, calibrates the probabilities.
  • Never trained on: the test documents, MDPBench, or the hard-page set.
  • Trained on Hugging Face Jobs with hf jobs uv run (a single self-contained script with its dependencies declared inline; see the Jobs guide): one A10G (a10g-large), about 23 minutes (1,353 to 1,368 s) per training run.