"""Evaluate all four turns of each sampled scan, with or without injected tilt.""" import argparse from concurrent.futures import ThreadPoolExecutor import hashlib import json from pathlib import Path import sys import threading import numpy as np from PIL import Image sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from folio_orient import PageOrienter, transpose_cw HERE = Path(__file__).resolve().parent def run(args): rows = json.loads((HERE / "pages.json").read_text()) jobs = [ (r, tilt, k) for r in rows if args.split in ("both", r["split"]) for tilt in (False, True) for k in range(4) ] local = threading.local() def evaluate(job): row, tilted, k = job if not hasattr(local, "model"): local.model = PageOrienter(args.model) im = Image.open(args.pages / row["file"]).convert("L") seed = int.from_bytes(hashlib.sha256(row["file"].encode()).digest()[:4], "big") tilt = (1.5 + seed % 550 / 100) * (-1 if seed % 2 else 1) if tilted else 0.0 if tilt: im = im.rotate( tilt, Image.Resampling.BICUBIC, expand=False, fillcolor=im.getpixel((0, 0)), ) im = transpose_cw(im, (-90 * k) % 360) result = local.model.estimate(im, deskew=False) return dict( file=row["file"], book=row["book"], page_type=row["page_type"], split=row["split"], target_cw=90 * k, tilt_ccw=tilt, **result ) with ThreadPoolExecutor(args.workers) as pool: predictions = list(pool.map(evaluate, jobs)) args.output.write_text(json.dumps(predictions, indent=1) + "\n") for split in ("dev", "test"): for kind in ("print", "plate_or_cover", "blank_or_showthrough"): for tilted in (False, True): subset = [ r for r in predictions if r["split"] == split and r["page_type"] == kind and bool(r["tilt_ccw"]) == tilted ] if not subset: continue correct = sum(r["target_cw"] == r["quarter_turn_cw"] for r in subset) abstain = sum(r["quarter_turn_cw"] is None for r in subset) print( split, kind, "tilted" if tilted else "clean", len(subset), correct, abstain, flush=True, ) if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("pages", type=Path) p.add_argument("model", type=Path) p.add_argument("output", type=Path) p.add_argument("--workers", type=int, default=2) p.add_argument("--split", choices=["dev", "test", "both"], default="both") run(p.parse_args())