page-script-id-agent / example.py
davanstrien's picture
davanstrien HF Staff
Add timm checkpoint (model.safetensors) and timm config; card: Use with timm
47907a2 verified
Raw History Blame Contribute Delete
1.51 kB
"""Page script identification with ONNX Runtime.
Usage: python example.py page.jpg [more pages ...]
Needs: pip install onnxruntime pillow numpy
"""
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})