davanstrien HF Staff commited on
Commit
8db42e3
·
verified ·
1 Parent(s): 75b02b2

Draft model card and files for review

Browse files
Files changed (4) hide show
  1. README.md +184 -0
  2. config.json +89 -0
  3. example.py +49 -0
  4. model.onnx +3 -0
README.md ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ # license: TO DECIDE before release (see the review notes below). No licence has been chosen.
3
+ library_name: onnx
4
+ pipeline_tag: image-classification
5
+ base_model: timm/mobilenetv4_conv_small.e2400_r224_in1k
6
+ tags:
7
+ - ocr
8
+ - script-identification
9
+ - page-classification
10
+ - document-ai
11
+ - multi-label
12
+ - onnx
13
+ - glam
14
+ ---
15
+
16
+ > **DRAFT — notes for review (delete this block before release)**
17
+ >
18
+ > 1. **Licence:** not chosen. The `license` field in the front matter is a placeholder comment.
19
+ > 2. **Backbone licence:** confirm the terms of `timm/mobilenetv4_conv_small.e2400_r224_in1k` (ImageNet-1k pretraining) from its model card.
20
+ > 3. **Training data rights:** the weights were trained on pages rendered from web PDFs (FinePDFs, from Common Crawl; the pages themselves are not released) and on labels from two third-party vision-language decision models (Valen-Decision-1.5-4B and Intern-Decision-4B, used where they agreed). Decide whether weights trained this way can be released as intended, and check both models' terms on using their outputs for training.
21
+ > 4. **Second-script threshold:** the agreed proposal says "report every script at 0.5". The one-script / two-script / unknown shares quoted below were measured with the threshold validated for this checkpoint (0.55), so `config.json` uses 0.55 and offers 0.5 for mixed-page search. A check made while preparing this card: at 0.5 the 2,056-page test set gives one script on 87.0% of pages and two or more on 7.8% (unknown unchanged). Pick one.
22
+ > 5. **Extra outputs:** the ONNX graph has 33 outputs; the first 12 are page-quality outputs from multi-task training, not documented or evaluated here. Consider re-exporting with the 21 script outputs only.
23
+ > 6. **Not verified for this card:** the MDPBench and Indra OCR names and citations; whether to ship the PyTorch checkpoint as well (the GPU speed figure is for PyTorch). Only one checkpoint (the best of three training seeds on validation pages) was exported.
24
+ > 7. Name, organisation, and whether this ships alone or with the text-amount and no-text models.
25
+
26
+ # Page script ID
27
+
28
+ 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.
29
+
30
+ MobileNetV4-conv-small, 2.5M parameters, 10 MB ONNX file. Greyscale page squashed to 640 × 640. 33 ms per page on one CPU thread, 12 ms on four (model only).
31
+
32
+ Scripts: Arabic, Armenian, Bengali, Cyrillic, Devanagari, Ethiopic, Georgian, Greek, Gujarati, Han, Hangul, Hebrew, Japanese, Kannada, Khmer, Latin, Malayalam, Myanmar, Tamil, Telugu, Thai.
33
+
34
+ ## Quick start
35
+
36
+ ```bash
37
+ pip install onnxruntime pillow numpy
38
+ python example.py page.jpg
39
+ ```
40
+
41
+ It prints the decision (a list of scripts, or `unknown`) and the three highest probabilities. `example.py` reads its settings from `config.json`:
42
+
43
+ ```python
44
+ import json
45
+ import sys
46
+ from pathlib import Path
47
+
48
+ import numpy as np
49
+ import onnxruntime as ort
50
+ from PIL import Image
51
+
52
+ HERE = Path(__file__).parent
53
+ CFG = json.loads((HERE / "config.json").read_text())
54
+ SESSION = ort.InferenceSession(str(HERE / CFG["model_file"]), providers=["CPUExecutionProvider"])
55
+ MEAN = np.array(CFG["mean"], np.float32).reshape(3, 1, 1)
56
+ STD = np.array(CFG["std"], np.float32).reshape(3, 1, 1)
57
+
58
+
59
+ def load_page(path):
60
+ size = CFG["input_size"]
61
+ im = Image.open(path)
62
+ if im.format == "JPEG":
63
+ im.draft("L", (2 * size, 2 * size)) # faster JPEG decode, as in training
64
+ grey = im.convert("L").resize((size, size), Image.BILINEAR) # squash, no crop
65
+ x = np.asarray(grey, np.float32) / 255.0
66
+ x = (np.repeat(x[None], 3, axis=0) - MEAN) / STD # grey copied to 3 channels
67
+ return x[None].astype(np.float32)
68
+
69
+
70
+ def script_probs(path):
71
+ logits = SESSION.run([CFG["output_name"]], {CFG["input_name"]: load_page(path)})[0][0]
72
+ z = logits[CFG["script_output_offset"]:] / CFG["temperature"]
73
+ return dict(zip(CFG["scripts"], (1 / (1 + np.exp(-z))).tolist()))
74
+
75
+
76
+ def decide(probs):
77
+ if max(probs.values()) < CFG["unknown_threshold"]:
78
+ return ["unknown"]
79
+ found = [s for s, p in probs.items() if p >= CFG["script_threshold"]]
80
+ return sorted(found, key=lambda s: -probs[s])
81
+
82
+
83
+ if __name__ == "__main__":
84
+ for path in sys.argv[1:]:
85
+ probs = script_probs(path)
86
+ top = sorted(probs.items(), key=lambda kv: -kv[1])[:3]
87
+ print(path, decide(probs), {s: round(p, 3) for s, p in top})
88
+ ```
89
+
90
+ Preprocessing matters: grey, bilinear squash to 640 × 640 (no crop, no padding), grey copied to three channels, ImageNet mean and std applied outside the graph. Script logits are divided by the temperature (2.3) before the sigmoid.
91
+
92
+ ## How to read the output
93
+
94
+ - **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.
95
+ - **One script:** one probability at or above the script threshold (0.55).
96
+ - **Several scripts:** two or more at or above it, usually a mixed page. To find mixed pages, lower the threshold to 0.5 (`mixed_page_threshold` in `config.json`).
97
+ - **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](https://huggingface.co/small-models-for-glam/page-ocr-flags).
98
+
99
+ 0.627 is the value at which 95% of 2,071 validation pages are still answered; the temperature was fitted on the same pages.
100
+
101
+ ## What it is for, and what it is not for
102
+
103
+ For full pages of documents: born-digital PDFs, office and library scans. Before you rely on it:
104
+
105
+ - **Full pages only.** On cropped text blocks it is unreliable and refuses most of them, whatever their script.
106
+ - **Weak on photographs.** On photographed documents it is right on 75% of pages, and the rule returns "unknown" for about half of them.
107
+ - **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.
108
+ - **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.
109
+
110
+ ## Evaluation
111
+
112
+ 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.
113
+
114
+ | Test pages | Label | n | This model | 3 seeds |
115
+ |---|---|---|---|---|
116
+ | Held-out pages of web PDFs, 25 languages | document language (wrong for about 6% of pages) | 2,695 | 92.2% | 91.6–92.2% |
117
+ | The same pages where the text layer is usable | script of the text layer | 2,056 | 92.2% | 91.7–92.2% |
118
+ | Held-out government documents, 21 scripts | text layer; document language for scans | 2,140 | 86.1% | 85.7–86.1% |
119
+ | MDPBench, digital renders | benchmark language | – | 90.4% | 88.8–90.4% |
120
+ | MDPBench, photographed | benchmark language | 2,040 | 74.8% | 74.8–77.4% |
121
+ | Hard pages: blackletter, rotated, non-Latin in old books | four models agreed (unanimous) | 113 | 91.2% | 90.3–92.9% |
122
+
123
+ **Against other ways of getting the script**, on the same 2,695 web-PDF pages and document-language label:
124
+
125
+ | Method | Accuracy | Cost |
126
+ |---|---|---|
127
+ | This model | 92.2% | 33 ms per page, one CPU thread |
128
+ | Script of the text from a full OCR pass (Indra OCR 1.2) | 96.4% | about 2.4 s per page per CPU core |
129
+ | Tesseract OSD | 55.0% | about 1.8 s per page |
130
+ | 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 |
131
+
132
+ 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.
133
+
134
+ **The decision rule** (thresholds 0.627 and 0.55):
135
+
136
+ | Test pages | n | One script (accuracy) | Two or more | Unknown |
137
+ |---|---|---|---|---|
138
+ | Web PDFs, text-layer label | 2,056 | 89.0% (95.0%) | 5.8% | 5.2% |
139
+ | Government documents | 2,140 | 83.6% (91.9%) | 4.9% | 11.5% |
140
+ | MDPBench, photographed | 2,040 | 48.6% (91.8%) | 1.9% | 49.5% |
141
+
142
+ **Mixed pages** (two or more scripts in the text layer; 247 web-PDF and 185 government pages): at 0.5 the exact set of scripts is returned on 36% and 40%, and at least one right script on 93% and 89%. Single-script pages given two scripts at 0.5: 1 to 3%.
143
+
144
+ **Blank pages:** of 1,048 held-out old-book pages with no OCR text, 1.9% are given a script.
145
+
146
+ **Unseen scripts.** The recipe was re-run twice with Georgian, Khmer and Telugu removed from training, then tested on 855 pages in those scripts:
147
+
148
+ | Outcome for a page in an unseen script | Run 1 | Run 2 |
149
+ |---|---|---|
150
+ | Returned as unknown | 68% | 67% |
151
+ | One wrong script (mostly Latin, Thai or Kannada, at about 0.75) | 26% | 28% |
152
+ | Two scripts | 6% | 5% |
153
+
154
+ By script: Georgian refused on 88–90% of pages, Khmer 61–65%, Telugu 47–54%.
155
+
156
+ ## Limits and failure modes
157
+
158
+ 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%.
159
+ 2. **Not supported:** scene text, handwriting, crops.
160
+ 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.
161
+ 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.
162
+ 5. **Optimistic numbers.** Most test pages come from the same collections as the training pages. Expect lower accuracy and more "unknown" elsewhere.
163
+ 6. **Weak labels.** Evaluation labels come from text layers, document metadata and model agreement. There is almost no human-labelled test data.
164
+ 7. **Synthetic unseen script.** Synthetic pages in a script held back from training (Gurmukhi) were refused on only 32% by this checkpoint.
165
+
166
+ ## Speed
167
+
168
+ 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.
169
+
170
+ | Setup | Time |
171
+ |---|---|
172
+ | ONNX Runtime, 1 CPU thread, batch 1 | 33.3 ms per page |
173
+ | ONNX Runtime, 4 CPU threads, batch 1 | 11.8 ms per page |
174
+ | PyTorch, A10G, bf16, batch 64 | 1,771 pages per second |
175
+
176
+ The ONNX file gives the same scores as the PyTorch checkpoint (largest logit difference 2.7e-5 on 100 pages).
177
+
178
+ ## Training
179
+
180
+ - **Born-digital pages** rendered from web PDFs in the FinePDFs dataset. 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.
181
+ - **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.
182
+ - **Negatives:** pages in scripts without a class (real Tibetan pages; synthetic Tibetan and Lao pages from [Synthdog-Multilingual-100](https://huggingface.co/datasets/WueNLP/Synthdog-Multilingual-100)), with every output at zero; this teaches "unknown". As many synthetic pages in trained scripts stop it learning "synthetic means unknown".
183
+ - **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.
184
+ - Never trained on: the test documents, MDPBench, or the hard-page set.
config.json ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_file": "model.onnx",
3
+ "input_name": "input",
4
+ "output_name": "logits",
5
+ "input_size": 640,
6
+ "input_layout": "float32, N x 3 x 640 x 640",
7
+ "colour": "greyscale page, the one grey channel copied to all three input channels",
8
+ "resize": "bilinear squash to 640 x 640 (aspect ratio not kept, no crop, no padding)",
9
+ "jpeg_draft": "for JPEG input, decode at reduced scale with PIL draft('L', (1280, 1280)) before the resize, as in training",
10
+ "normalisation": "outside the graph: x / 255, then (x - mean) / std per channel",
11
+ "mean": [
12
+ 0.485,
13
+ 0.456,
14
+ 0.406
15
+ ],
16
+ "std": [
17
+ 0.229,
18
+ 0.224,
19
+ 0.225
20
+ ],
21
+ "script_output_offset": 12,
22
+ "auxiliary_outputs": [
23
+ "no_text",
24
+ "lo_blank_write",
25
+ "lo_trunc",
26
+ "lo_loop",
27
+ "faint",
28
+ "table",
29
+ "dense",
30
+ "showthrough",
31
+ "real_text",
32
+ "no_marks",
33
+ "text_amount",
34
+ "cheap_ocr_ok"
35
+ ],
36
+ "auxiliary_outputs_note": "logits 0 to 11 come from multi-task training; they are not documented or evaluated for this release. Ignore them.",
37
+ "scripts": [
38
+ "Arab",
39
+ "Beng",
40
+ "Cyrl",
41
+ "Deva",
42
+ "Grek",
43
+ "Hang",
44
+ "Hani",
45
+ "Hebr",
46
+ "Jpan",
47
+ "Latn",
48
+ "Taml",
49
+ "Thai",
50
+ "Armn",
51
+ "Ethi",
52
+ "Geor",
53
+ "Gujr",
54
+ "Khmr",
55
+ "Knda",
56
+ "Mlym",
57
+ "Mymr",
58
+ "Telu"
59
+ ],
60
+ "script_names": {
61
+ "Arab": "Arabic",
62
+ "Beng": "Bengali",
63
+ "Cyrl": "Cyrillic",
64
+ "Deva": "Devanagari",
65
+ "Grek": "Greek",
66
+ "Hang": "Hangul",
67
+ "Hani": "Han",
68
+ "Hebr": "Hebrew",
69
+ "Jpan": "Japanese",
70
+ "Latn": "Latin",
71
+ "Taml": "Tamil",
72
+ "Thai": "Thai",
73
+ "Armn": "Armenian",
74
+ "Ethi": "Ethiopic",
75
+ "Geor": "Georgian",
76
+ "Gujr": "Gujarati",
77
+ "Khmr": "Khmer",
78
+ "Knda": "Kannada",
79
+ "Mlym": "Malayalam",
80
+ "Mymr": "Myanmar",
81
+ "Telu": "Telugu"
82
+ },
83
+ "temperature": 2.3,
84
+ "probability": "sigmoid(logit / temperature), independently for each script",
85
+ "unknown_threshold": 0.6271,
86
+ "script_threshold": 0.55,
87
+ "rule": "if the largest script probability is below unknown_threshold, the page is 'unknown'; otherwise report every script with probability >= script_threshold (0.55, chosen on validation pages for this checkpoint). Use mixed_page_threshold (0.5) instead when finding mixed-script pages matters more than a clean single answer.",
88
+ "mixed_page_threshold": 0.5
89
+ }
example.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Page script identification with ONNX Runtime.
2
+
3
+ Usage: python example.py page.jpg [more pages ...]
4
+ Needs: pip install onnxruntime pillow numpy
5
+ """
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import onnxruntime as ort
12
+ from PIL import Image
13
+
14
+ HERE = Path(__file__).parent
15
+ CFG = json.loads((HERE / "config.json").read_text())
16
+ SESSION = ort.InferenceSession(str(HERE / CFG["model_file"]), providers=["CPUExecutionProvider"])
17
+ MEAN = np.array(CFG["mean"], np.float32).reshape(3, 1, 1)
18
+ STD = np.array(CFG["std"], np.float32).reshape(3, 1, 1)
19
+
20
+
21
+ def load_page(path):
22
+ size = CFG["input_size"]
23
+ im = Image.open(path)
24
+ if im.format == "JPEG":
25
+ im.draft("L", (2 * size, 2 * size)) # faster JPEG decode, as in training
26
+ grey = im.convert("L").resize((size, size), Image.BILINEAR) # squash, no crop
27
+ x = np.asarray(grey, np.float32) / 255.0
28
+ x = (np.repeat(x[None], 3, axis=0) - MEAN) / STD # grey copied to 3 channels
29
+ return x[None].astype(np.float32)
30
+
31
+
32
+ def script_probs(path):
33
+ logits = SESSION.run([CFG["output_name"]], {CFG["input_name"]: load_page(path)})[0][0]
34
+ z = logits[CFG["script_output_offset"]:] / CFG["temperature"]
35
+ return dict(zip(CFG["scripts"], (1 / (1 + np.exp(-z))).tolist()))
36
+
37
+
38
+ def decide(probs):
39
+ if max(probs.values()) < CFG["unknown_threshold"]:
40
+ return ["unknown"]
41
+ found = [s for s, p in probs.items() if p >= CFG["script_threshold"]]
42
+ return sorted(found, key=lambda s: -probs[s])
43
+
44
+
45
+ if __name__ == "__main__":
46
+ for path in sys.argv[1:]:
47
+ probs = script_probs(path)
48
+ top = sorted(probs.items(), key=lambda kv: -kv[1])[:3]
49
+ print(path, decide(probs), {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:45cb67e0371f00eb77180067df20df50ba248dc97979b3dfd0ca5f02fed8057b
3
+ size 10114117