Add installable offline CLI, lossless PDF quarter-turns, fast mode, edge-matched padding and reproducible OCR and DocLayNet evaluations
a4cdb00 verified Download evaluation/compare.py from foliokestrel/folio-orient: direct link, hf CLI and curl.
- Browser
- Download file 4.73 kB
-
https://huggingface.co/foliokestrel/folio-orient/resolve/main/evaluation/compare.py
- Command line
-
hf download hf://foliokestrel/folio-orient/evaluation/compare.py
-
curl -L -o compare.py https://huggingface.co/foliokestrel/folio-orient/resolve/main/evaluation/compare.py
4.73 kB
| """Compare two CPU pipelines on identical views. The Paddle export is evaluation-only.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| from tempfile import TemporaryDirectory | |
| import platform | |
| from pathlib import Path | |
| from time import perf_counter | |
| import sys | |
| from urllib.request import urlretrieve | |
| import numpy as np | |
| import onnxruntime as ort | |
| from PIL import Image | |
| root = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(root)) | |
| from folio_orient import PageOrienter, fine_skew, transpose_cw | |
| model_url = "https://huggingface.co/monkt/paddleocr-onnx/resolve/7b02d0a30a07ba2b92ad1ff5a8941ae2c633de65/preprocessing/doc-orientation/PP-LCNet_x1_0_doc_ori.onnx" | |
| def run(pages, output, directory): | |
| paddle = directory / "baseline-tmp.onnx" | |
| urlretrieve(model_url, paddle) | |
| opts = ort.SessionOptions() | |
| opts.intra_op_num_threads = 1 | |
| session = ort.InferenceSession( | |
| str(paddle), opts, providers=["CPUExecutionProvider"] | |
| ) | |
| input_name = session.get_inputs()[0].name | |
| model = PageOrienter(root / "model.onnx") | |
| mean = np.array([0.485, 0.456, 0.406], dtype=np.float32) | |
| std = np.array([0.229, 0.224, 0.225], dtype=np.float32) | |
| def baseline(im): | |
| import cv2 | |
| # Follow Paddle's resize_short:256, center crop 224, channel normalization. | |
| cv2.setNumThreads(1) | |
| view = np.asarray(im) | |
| h, w = view.shape | |
| scale = 256 / min(h, w) | |
| resized = cv2.resize( | |
| view, (round(w * scale), round(h * scale)), interpolation=cv2.INTER_LINEAR | |
| ) | |
| h, w = resized.shape | |
| top = (h - 224) // 2 | |
| left = (w - 224) // 2 | |
| view = resized[top : top + 224, left : left + 224] | |
| rgb = (view[:, :, None].astype(np.float32) / 255 - mean) / std | |
| scores = session.run(None, {input_name: rgb.transpose(2, 0, 1)[None].copy()})[0] | |
| # PaddleX passes its label to cv2.getRotationMatrix2D as a positive CCW correction. | |
| return int(-90 * scores.reshape(-1).argmax()) % 360 | |
| rows = json.loads((root / "evaluation/pages.json").read_text()) | |
| pred = [] | |
| for row in rows: | |
| if row["split"] != "test" or row["page_type"] != "print": | |
| continue | |
| im = Image.open(pages / row["file"]).convert("L") | |
| seed = int.from_bytes(hashlib.sha256(row["file"].encode()).digest()[:4], "big") | |
| for tilt in [0.0, (1.5 + seed % 550 / 100) * (-1 if seed % 2 else 1)]: | |
| upright = ( | |
| im.rotate( | |
| tilt, | |
| Image.Resampling.BICUBIC, | |
| expand=False, | |
| fillcolor=im.getpixel((0, 0)), | |
| ) | |
| if tilt | |
| else im | |
| ) | |
| skew = fine_skew(upright) | |
| for k in range(4): | |
| view = transpose_cw(upright, (-90 * k) % 360) | |
| tick = perf_counter() | |
| result = baseline(view) | |
| base_ms = 1000 * (perf_counter() - tick) | |
| tick = perf_counter() | |
| ours = model.estimate(view, deskew=False) | |
| folio_ms = 1000 * (perf_counter() - tick) | |
| pred.append( | |
| dict( | |
| file=row["file"], | |
| tilt_ccw=tilt, | |
| target_cw=k * 90, | |
| baseline_cw=result, | |
| folio_cw=ours["quarter_turn_cw"], | |
| baseline_ms=base_ms, | |
| folio_ms=folio_ms, | |
| skew_cw=skew, | |
| ) | |
| ) | |
| for tilted in (False, True): | |
| subset = [p for p in pred if bool(p["tilt_ccw"]) == tilted] | |
| print( | |
| "tilted", | |
| tilted, | |
| len(subset), | |
| { | |
| model: sum(p[model + "_cw"] == p["target_cw"] for p in subset) | |
| for model in ("baseline", "folio") | |
| }, | |
| flush=True, | |
| ) | |
| print( | |
| "median times", | |
| { | |
| m: float(np.median([p[m + "_ms"] for p in pred[2:]])) | |
| for m in ["baseline", "folio"] | |
| }, | |
| flush=True, | |
| ) | |
| output.write_text( | |
| json.dumps( | |
| { | |
| "baseline_url": model_url, | |
| "platform": platform.platform(), | |
| "onnxruntime": ort.__version__, | |
| "predictions": pred, | |
| }, | |
| indent=1, | |
| ) | |
| ) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("scans", type=Path) | |
| parser.add_argument("output", type=Path) | |
| args = parser.parse_args() | |
| with TemporaryDirectory() as directory: | |
| run(args.scans, args.output, Path(directory)) | |