"""Decide whether a single book scan shows a spread using ONNX Runtime on CPU.""" import argparse from hashlib import sha256 import json from pathlib import Path import numpy as np from PIL import Image, ImageOps import onnxruntime as ort def display(image): if getattr(image, "n_frames", 1) != 1: raise ValueError("Select one frame before scoring a multi-frame file.") image = ImageOps.exif_transpose(image) if "A" in image.getbands() or "transparency" in image.info: rgba = image.convert("RGBA") paper = Image.new("RGB", rgba.size, "white") paper.paste(rgba, mask=rgba.getchannel("A")) return paper return image.convert("RGB") class LayoutProbe: def __init__(self, directory, threads=2, compact=False): directory = Path(directory) cfg = json.loads((directory / "config.json").read_text()) if compact: variant = cfg.get("variants", {}).get("compact") if not variant or variant.get("file") != "compact/model.onnx": raise ValueError("This config.json does not specify the compact model.") model = directory / "compact" / "model.onnx" checksum = variant["sha256"] else: model = directory / "model.onnx" checksum = cfg["sha256"] if threads < 1: raise ValueError("The thread count must be positive.") digest = sha256() with model.open("rb") as stream: for block in iter(lambda: stream.read(1024*1024), b""): digest.update(block) if digest.hexdigest() != checksum: raise ValueError("Model checksum differs from config.json.") if cfg["heads"] != ["original", "mount_trained"]: raise ValueError("Unexpected layout head order.") options = ort.SessionOptions() options.intra_op_num_threads = threads options.inter_op_num_threads = 1 self.session = ort.InferenceSession(str(model), sess_options=options, providers=["CPUExecutionProvider"]) self.cfg = cfg def predict(self, image): frame = display(image).resize((224,224), Image.Resampling.BICUBIC) scores = self.session.run([self.cfg["output"]], {self.cfg["input"]: np.asarray(frame)})[0] if scores.shape != (2,) or not np.isfinite(scores).all(): raise ValueError("Invalid layout scores.") result = {} for name, value in zip(self.cfg["heads"], scores): score = float(value) if score <= self.cfg["whole_max"]: action = "whole" elif score >= self.cfg["split_min"]: action = "split" else: action = "review" result[name] = {"score":score, "proposal":"split" if score>0.5 else "whole", "action":action} return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("--model-dir", type=Path, default=Path(__file__).resolve().parent) parser.add_argument("--threads", type=int, default=2) parser.add_argument("--compact", action="store_true", help="Use the smaller download in compact/model.onnx.") parser.add_argument("--compare", action="store_true", help="Include the experimental mount-trained result.") args = parser.parse_args() try: probe = LayoutProbe(args.model_dir, args.threads, compact=args.compact) with Image.open(args.image) as image: result = probe.predict(image) except (OSError,ValueError) as error: parser.exit(1,f"{parser.prog}: {error}\n") print(json.dumps(result if args.compare else result["original"],allow_nan=False)) if __name__=="__main__": main()