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-hgnet with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- timm
How to use davanstrien/page-script-id-hgnet with timm:
import timm model = timm.create_model("hf-hub:davanstrien/page-script-id-hgnet", pretrained=True) - Notebooks
- Google Colab
- Kaggle
File size: 2,458 Bytes
a351116 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | """Page script identification with ONNX Runtime.
Usage:
python example.py page.jpg [more pages ...]
python example.py --pad crop.jpg # for wide text-block crops
python example.py --mixed page.jpg # lower second-script threshold (0.50)
Needs: pip install onnxruntime pillow numpy
"""
import argparse
import json
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"]
SESSION = ort.InferenceSession(str(HERE / CFG["onnx_file"]), providers=["CPUExecutionProvider"])
def load_page(path, pad_square=False):
size = CFG["input_size"]
im = Image.open(path)
if im.format == "JPEG" and not pad_square:
im.draft("L", (2 * size, 2 * size)) # faster JPEG decode, as in training
grey = im.convert("L")
if pad_square:
w, h = grey.size
s = max(w, h)
canvas = Image.new("L", (s, s), 255)
canvas.paste(grey, ((s - w) // 2, (s - h) // 2))
grey = canvas
grey = grey.resize((size, size), Image.BILINEAR)
return np.asarray(grey, np.float32)[None] # 0..255; norm + temp + sigmoid are inside ONNX
def script_probs(path, pad_square=False):
probs = SESSION.run([CFG["onnx_output_name"]], {CFG["onnx_input_name"]: load_page(path, pad_square=pad_square)})[0][0]
return dict(zip(CFG["scripts"], probs.tolist()))
def decide(probs, threshold=CFG["script_threshold"], unknown_threshold=CFG["unknown_threshold"]):
if max(probs.values()) < unknown_threshold:
return ["unknown"]
found = [s for s, p in probs.items() if p >= threshold]
if not found:
found = [max(probs, key=probs.get)]
return sorted(found, key=lambda s: -probs[s])
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("paths", nargs="+")
ap.add_argument("--pad", action="store_true", help="Pad image to a white square (recommended for text-block crops)")
ap.add_argument("--mixed", action="store_true", help="Use mixed_page_threshold (0.50) instead of 0.55")
args = ap.parse_args()
thr = CFG["mixed_page_threshold"] if args.mixed else CFG["script_threshold"]
for path in args.paths:
probs = script_probs(path, pad_square=args.pad)
top = sorted(probs.items(), key=lambda kv: -kv[1])[:3]
print(path, decide(probs, threshold=thr), {s: round(p, 3) for s, p in top})
|