page-script-id / example.py
davanstrien's picture
davanstrien HF Staff
Upload page-script-id-v2 (distilled MobileNetV4-Small 640px, FP32 ONNX + timm + card)
b9c06e5 verified
Raw History Blame Contribute Delete
2.46 kB
"""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})