File size: 1,513 Bytes
8db42e3
 
 
 
 
 
 
 
 
 
 
 
 
 
47907a2
 
8db42e3
 
 
 
 
 
 
 
ebe3a5d
8db42e3
 
 
47907a2
ebe3a5d
8db42e3
 
ebe3a5d
8db42e3
 
ebe3a5d
8db42e3
 
 
 
 
 
 
 
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
"""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})