"""Inspect each PDF page and optionally write a copy with corrected quarter-turns.""" import argparse from contextlib import closing import json import os from pathlib import Path from tempfile import NamedTemporaryFile from folio_orient import PageOrienter def inspect_pages(document, orienter, min_agreement, apply, *, fast=False): for number in range(len(document)): with closing(document[number]) as page: original = page.get_rotation() scale = 1600 / max(page.get_size()) with closing(page.render(scale=scale, grayscale=True)) as bitmap: estimate = orienter.estimate(bitmap.to_pil(), deskew=False, fast=fast) turn = estimate["quarter_turn_cw"] accepted = turn is not None and estimate["agreement"] >= min_agreement new_rotation = (original + turn) % 360 if accepted else original if apply and new_rotation != original: page.set_rotation(new_rotation) yield { "page": number + 1, "existing_rotation": original, "quarter_turn_cw": turn, "agreement": estimate["agreement"], "patches": estimate["patches"], "accepted": accepted, "output_rotation": new_rotation, } def save_copy(document, destination): # Stage beside the target and expose the result only after PDFium finishes. with NamedTemporaryFile(dir=destination.parent, delete=False) as tmp: path = Path(tmp.name) try: document.save(path) os.link(path, destination) finally: path.unlink(missing_ok=True) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("pdf", type=Path) parser.add_argument( "--output", type=Path, help="Write a new PDF with accepted page rotations" ) parser.add_argument( "--fast", action="store_true", help="Try a smaller patch sample first" ) parser.add_argument("--min-agreement", type=float, default=0.70) parser.add_argument("--model", type=Path, help="Path to a Folio Orient ONNX model") args = parser.parse_args() if not 0 <= args.min_agreement <= 1: parser.error("--min-agreement must be between 0 and 1") if args.output is not None and args.output.exists(): parser.error("output already exists") try: import pypdfium2 as pdfium except ImportError: parser.error("Install the PDF dependency with python -m pip install pypdfium2") orienter = PageOrienter(args.model) with pdfium.PdfDocument(args.pdf) as pdf: for row in inspect_pages( pdf, orienter, args.min_agreement, args.output is not None, fast=args.fast ): print(json.dumps(row), flush=True) if args.output is not None: save_copy(pdf, args.output) if __name__ == "__main__": main()