Image Classification
timm
ONNX
Safetensors
ocr
script-identification
page-classification
document-ai
multi-label
glam
hf_jobs
Instructions to use davanstrien/page-script-id-agent with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- timm
How to use davanstrien/page-script-id-agent with timm:
import timm model = timm.create_model("hf-hub:davanstrien/page-script-id-agent", pretrained=True) - Notebooks
- Google Colab
- Kaggle
Revise draft after review: Apache-2.0, cleaner ONNX, threshold explanation, hf_jobs tag
Browse files- README.md +24 -23
- config.json +13 -79
- example.py +5 -10
- model.onnx +2 -2
README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
---
|
| 2 |
-
|
| 3 |
library_name: onnx
|
| 4 |
pipeline_tag: image-classification
|
| 5 |
base_model: timm/mobilenetv4_conv_small.e2400_r224_in1k
|
|
@@ -11,17 +11,13 @@ tags:
|
|
| 11 |
- multi-label
|
| 12 |
- onnx
|
| 13 |
- glam
|
|
|
|
| 14 |
---
|
| 15 |
|
| 16 |
> **DRAFT — notes for review (delete this block before release)**
|
| 17 |
>
|
| 18 |
-
> 1. **Licence:**
|
| 19 |
-
> 2. **
|
| 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 |
|
|
@@ -52,8 +48,6 @@ from PIL import Image
|
|
| 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):
|
|
@@ -62,21 +56,18 @@ def load_page(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 |
-
|
| 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 |
-
|
| 72 |
-
|
| 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 >=
|
| 80 |
return sorted(found, key=lambda s: -probs[s])
|
| 81 |
|
| 82 |
|
|
@@ -87,17 +78,26 @@ if __name__ == "__main__":
|
|
| 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),
|
| 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.
|
| 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:
|
|
@@ -139,7 +139,7 @@ If you run full OCR anyway, its text gives a better script label; this model is
|
|
| 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
|
| 143 |
|
| 144 |
**Blank pages:** of 1,048 held-out old-book pages with no OCR text, 1.9% are given a script.
|
| 145 |
|
|
@@ -173,12 +173,13 @@ Model forward pass only, on random input, on a 48-vCPU cloud machine with one A1
|
|
| 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
|
| 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.
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
library_name: onnx
|
| 4 |
pipeline_tag: image-classification
|
| 5 |
base_model: timm/mobilenetv4_conv_small.e2400_r224_in1k
|
|
|
|
| 11 |
- multi-label
|
| 12 |
- onnx
|
| 13 |
- glam
|
| 14 |
+
- hf_jobs
|
| 15 |
---
|
| 16 |
|
| 17 |
> **DRAFT — notes for review (delete this block before release)**
|
| 18 |
>
|
| 19 |
+
> 1. **Licence:** Apache-2.0 is set. Basis, from the licence fields on the Hub as checked on 2026-11-25: backbone `timm/mobilenetv4_conv_small.e2400_r224_in1k` Apache-2.0; the labelling models Valen-Decision-1.5-4B and Intern-Decision-4B Apache-2.0; Synthdog-Multilingual-100 Apache-2.0; FinePDFs ODC-By (attribution, given under Training); the sibling models page-ocr-flags and text-page-filter Apache-2.0. The pages themselves (web PDFs, library scans) carry their own rights, which is why only weights are released. This is a reading of licence fields, not legal advice.
|
| 20 |
+
> 2. **Still open:** whether to also ship the PyTorch/timm checkpoint (the GPU speed figure is for PyTorch); the MDPBench and Indra OCR citations are not verified; only one checkpoint (the best of three training seeds on validation pages) was exported.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# Page script ID
|
| 23 |
|
|
|
|
| 48 |
HERE = Path(__file__).parent
|
| 49 |
CFG = json.loads((HERE / "config.json").read_text())
|
| 50 |
SESSION = ort.InferenceSession(str(HERE / CFG["model_file"]), providers=["CPUExecutionProvider"])
|
|
|
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
def load_page(path):
|
|
|
|
| 56 |
if im.format == "JPEG":
|
| 57 |
im.draft("L", (2 * size, 2 * size)) # faster JPEG decode, as in training
|
| 58 |
grey = im.convert("L").resize((size, size), Image.BILINEAR) # squash, no crop
|
| 59 |
+
return np.asarray(grey, np.float32)[None] # 0..255; everything else is inside the model
|
|
|
|
|
|
|
| 60 |
|
| 61 |
|
| 62 |
def script_probs(path):
|
| 63 |
+
probs = SESSION.run([CFG["output_name"]], {CFG["input_name"]: load_page(path)})[0][0]
|
| 64 |
+
return dict(zip(CFG["scripts"], probs.tolist()))
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
+
def decide(probs, threshold=CFG["script_threshold"]):
|
| 68 |
if max(probs.values()) < CFG["unknown_threshold"]:
|
| 69 |
return ["unknown"]
|
| 70 |
+
found = [s for s, p in probs.items() if p >= threshold]
|
| 71 |
return sorted(found, key=lambda s: -probs[s])
|
| 72 |
|
| 73 |
|
|
|
|
| 78 |
print(path, decide(probs), {s: round(p, 3) for s, p in top})
|
| 79 |
```
|
| 80 |
|
| 81 |
+
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.
|
| 82 |
|
| 83 |
## How to read the output
|
| 84 |
|
| 85 |
- **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.
|
| 86 |
- **One script:** one probability at or above the script threshold (0.55).
|
| 87 |
+
- **Several scripts:** two or more at or above it, usually a mixed page.
|
| 88 |
- **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).
|
| 89 |
|
| 90 |
0.627 is the value at which 95% of 2,071 validation pages are still answered; the temperature was fitted on the same pages.
|
| 91 |
|
| 92 |
+
**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):
|
| 93 |
+
|
| 94 |
+
| Script threshold | Two or more scripts | Single-script pages given two | Mixed pages (247): exact set | Mixed pages: at least one right |
|
| 95 |
+
|---|---|---|---|---|
|
| 96 |
+
| 0.55 (default) | 5.8% | 1.8% | 29.1% | 86.2% |
|
| 97 |
+
| 0.5 | 7.8% | 3.0% | 36.0% | 86.6% |
|
| 98 |
+
|
| 99 |
+
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.
|
| 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:
|
|
|
|
| 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): 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%.
|
| 143 |
|
| 144 |
**Blank pages:** of 1,048 held-out old-book pages with no OCR text, 1.9% are given a script.
|
| 145 |
|
|
|
|
| 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 |
+
CPU times were measured on an earlier export of the same network with the normalisation and temperature outside the graph. The ONNX file gives the same probabilities as the PyTorch checkpoint (largest difference 1.7e-6 on 400 pages).
|
| 177 |
|
| 178 |
## Training
|
| 179 |
|
| 180 |
+
- **Born-digital pages** rendered from web PDFs in the [FinePDFs](https://huggingface.co/datasets/HuggingFaceFW/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.
|
| 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.
|
| 185 |
+
- Trained on Hugging Face Jobs: one A10G (`a10g-large`), about 23 minutes (1,353 to 1,368 s) per training run.
|
config.json
CHANGED
|
@@ -1,89 +1,23 @@
|
|
| 1 |
{
|
| 2 |
"model_file": "model.onnx",
|
| 3 |
-
"input_name": "
|
| 4 |
-
"output_name": "
|
| 5 |
"input_size": 640,
|
| 6 |
-
"input_layout": "float32, N x
|
| 7 |
-
"colour": "greyscale page,
|
| 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 |
-
"
|
| 11 |
-
"
|
| 12 |
-
|
| 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 |
-
"
|
| 63 |
-
"
|
| 64 |
-
"
|
| 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 |
-
"
|
| 88 |
-
"
|
| 89 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"model_file": "model.onnx",
|
| 3 |
+
"input_name": "grey",
|
| 4 |
+
"output_name": "probabilities",
|
| 5 |
"input_size": 640,
|
| 6 |
+
"input_layout": "float32, N x 640 x 640, grey values 0 to 255 (no channel axis)",
|
| 7 |
+
"colour": "greyscale page, one channel",
|
| 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 |
+
"inside_the_model": "x / 255, grey copied to three channels, ImageNet mean and std, temperature (2.3), sigmoid",
|
| 11 |
+
"output": "N x 21 independent script probabilities, in the order of 'scripts'",
|
| 12 |
+
"scripts": ["Arab", "Beng", "Cyrl", "Deva", "Grek", "Hang", "Hani", "Hebr", "Jpan", "Latn", "Taml", "Thai", "Armn", "Ethi", "Geor", "Gujr", "Khmr", "Knda", "Mlym", "Mymr", "Telu"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
"script_names": {
|
| 14 |
+
"Arab": "Arabic", "Beng": "Bengali", "Cyrl": "Cyrillic", "Deva": "Devanagari", "Grek": "Greek",
|
| 15 |
+
"Hang": "Hangul", "Hani": "Han", "Hebr": "Hebrew", "Jpan": "Japanese", "Latn": "Latin",
|
| 16 |
+
"Taml": "Tamil", "Thai": "Thai", "Armn": "Armenian", "Ethi": "Ethiopic", "Geor": "Georgian",
|
| 17 |
+
"Gujr": "Gujarati", "Khmr": "Khmer", "Knda": "Kannada", "Mlym": "Malayalam", "Mymr": "Myanmar", "Telu": "Telugu"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
},
|
|
|
|
|
|
|
| 19 |
"unknown_threshold": 0.6271,
|
| 20 |
"script_threshold": 0.55,
|
| 21 |
+
"mixed_page_threshold": 0.5,
|
| 22 |
+
"rule": "if the largest probability is below unknown_threshold, the page is 'unknown'; otherwise report every script with probability >= script_threshold. Use mixed_page_threshold instead when finding mixed-script pages matters more than a clean single answer."
|
| 23 |
}
|
example.py
CHANGED
|
@@ -14,8 +14,6 @@ from PIL import Image
|
|
| 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):
|
|
@@ -24,21 +22,18 @@ def load_page(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 |
-
|
| 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 |
-
|
| 34 |
-
|
| 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 >=
|
| 42 |
return sorted(found, key=lambda s: -probs[s])
|
| 43 |
|
| 44 |
|
|
|
|
| 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 |
|
| 18 |
|
| 19 |
def load_page(path):
|
|
|
|
| 22 |
if im.format == "JPEG":
|
| 23 |
im.draft("L", (2 * size, 2 * size)) # faster JPEG decode, as in training
|
| 24 |
grey = im.convert("L").resize((size, size), Image.BILINEAR) # squash, no crop
|
| 25 |
+
return np.asarray(grey, np.float32)[None] # 0..255; everything else is inside the model
|
|
|
|
|
|
|
| 26 |
|
| 27 |
|
| 28 |
def script_probs(path):
|
| 29 |
+
probs = SESSION.run([CFG["output_name"]], {CFG["input_name"]: load_page(path)})[0][0]
|
| 30 |
+
return dict(zip(CFG["scripts"], probs.tolist()))
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
+
def decide(probs, threshold=CFG["script_threshold"]):
|
| 34 |
if max(probs.values()) < CFG["unknown_threshold"]:
|
| 35 |
return ["unknown"]
|
| 36 |
+
found = [s for s, p in probs.items() if p >= threshold]
|
| 37 |
return sorted(found, key=lambda s: -probs[s])
|
| 38 |
|
| 39 |
|
model.onnx
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9f09be770b3d691cd34450cdab318960fd60f9ca9f18775e25285091242d71a9
|
| 3 |
+
size 10116583
|