#!/usr/bin/env python3 """Complete local Python-package example. The packages download missing weights. Install package-requirements.txt in a Python 3.12 virtual environment. Keep model-manifest.json beside this file. For already-downloaded ONNX files, use local-onnx.py instead; it makes no network requests. """ from __future__ import annotations import argparse import json from pathlib import Path import capybara as cb import cv2 import numpy as np from PIL import Image, ImageOps cv2.setNumThreads(1) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--release", required=True) parser.add_argument("--image", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists(): parser.error("Choose a new output directory") manifest = json.loads(Path(__file__).with_name("model-manifest.json").read_text()) release = next((item for item in manifest["releases"] if item["id"] == args.release), None) if release is None: parser.error("Choose a release from model-manifest.json") if args.image.stat().st_size > 10 * 1024 * 1024: parser.error("Image exceeds 10 MiB") with Image.open(args.image) as source: if source.format not in {"JPEG", "PNG", "WEBP"} or source.width * source.height > 40_000_000 or getattr(source, "n_frames", 1) != 1: parser.error("Use a still JPEG, PNG or WebP up to 40 megapixels") rgba = ImageOps.exif_transpose(source).convert("RGBA") canvas = Image.new("RGBA", rgba.size, "white") canvas.alpha_composite(rgba) canvas = canvas.convert("RGB") canvas.thumbnail((1600, 1600), Image.Resampling.LANCZOS) image = np.ascontiguousarray(np.asarray(canvas)[:, :, ::-1]) if release["product"] == "docaligner": from docaligner import DocAligner model = DocAligner(**release["configuration"], backend=cb.Backend.cpu, session_option={"intra_op_num_threads": 1, "inter_op_num_threads": 1}) polygon = model(image, do_center_crop=False) result = {"polygon": polygon.tolist()} else: from mrzscanner import MRZScanner model = MRZScanner(**release["configuration"], backend=cb.Backend.cpu, session_option={"intra_op_num_threads": 1, "inter_op_num_threads": 1}) response = model(image, do_center_crop=False, do_postprocess=False) polygon = response["mrz_polygon"] result = {"mrz_polygon": polygon.tolist() if polygon is not None else None, "mrz_texts": response["mrz_texts"], "message": response["msg"].value} args.output.mkdir(mode=0o700, parents=True) result.update(model_version=release["id"], image_width=image.shape[1], image_height=image.shape[0]) (args.output / "result.json").write_text(json.dumps(result, indent=2) + "\n") if polygon is not None and np.asarray(polygon).shape == (4, 2): cv2.polylines(image, [np.rint(polygon).astype(np.int32)], True, (0, 140, 255), 3) if not cv2.imwrite(str(args.output / "overlay.png"), image): raise OSError("Unable to save overlay") print("Saved result.json and overlay.png locally. Review the output against your image.") if __name__ == "__main__": main()