页面简介
Check the values an OCR extractor read from invoice photos: Jev boxes each value, scores it against the page and against a crop of its box, and flags low scores for review.
正文摘录
Values that OCR extracts from invoice photos are mostly right, but checking every one by hand takes as long as typing them in. Jev can check them instead: it boxes each value on the photo and flags the ones that look wrong, so a reviewer only looks at those. On these two supplier invoices, an extractor read the supplier, invoice number, date, amount due and bank details, and got three values wrong. Jev flags all three. Jev checks each value twice: against the whole page (the page check) and against a crop of its box (the crop check). A value that scores below 0.25 on either check goes to review. In the table, “extracted” is what the extractor read and “printed” is what the invoice says. invoicefieldextractedprintedpage checkcrop checkMilkwoodinvoice numberAN400074IN4000740.880.18Siyakhulainvoice numberINV03070INV030790.020.04Siyakhuladate16/09/202816/09/20260.170.66 The code below starts from extractions.json, the values the OCR and LLM steps produced, and leaves those two steps out. You can make that file with Tesseract and your LLM of choice. Setup Run in ColabRuns as published without an API key.Python fileThis page as one .py file, to run locally. To run it on your own machine instead: pip install ipython pillow 'typesafe-sdk[pil]>=0.7.5' 'cooksafe>=0.3.0,<0.4.0' With uv, uv run ocr_confidence_bounding_boxes.py installs the dependencies for you. The code replays saved answers, so it runs as published without an API key. To change a request, set TYPESAFE_API_KEY; in Colab, add it in the Secrets panel. Note - Images and Box questions are dreamer-ready, which means they are not yet ready for production, and their request format and answers can change between releases. They need Jev 1.14, and every request needs the TypeSafe-Danger-Zone-Images: true header. The client below sets that header. The numbers below came from jev-1.14.0 on 2026-10-15. import io import json import os import urllib.request from pathlib import Path from cooksafe import JsonCache from IPython.display import display from PIL import Image as PILImage from PIL import ImageDraw, ImageFont from typesafe_sdk import Box, Image, Noul, SystemOneResponse, TypeSafeClient # Box questions need Jev 1.14 or later. TYPESAFE_MODEL = "jev-1.14.0" # the page's model; "jev-latest" runs the newest, live BAR = 0.25 # a check scoring below this flags the field ZOOM = 3 # the zoomed region is three times the first box, and at least ZOOM_MIN of the page ZOOM_MIN = (0.30, 0.15) # width, height as fractions of the page GROW = (0.25, 0.20) # review margin around each box, as fractions of its width and height MIN_SIDE, MAX_SIDE = 280, 1568 # the pixel range Jev accepts for each side of an image # The keys this cookbook uses. In Colab, keys saved in the Secrets panel are copied in here. KEYS = ["TYPESAFE_API_KEY"] try: from google.colab import userdata except ImportError: # not in Colab userdata = None for key in KEYS: if userdata is not None and key not in os.environ: try: os.environ[key] = userdata.get(key) except (userdata.SecretNotFoundError, userdata.NotebookAccessError): pass # not saved, or this notebook may not read it client = TypeSafeClient( api_key=os.environ.get("TYPESAFE_API_KEY", "cache-only"), # keyless kernels replay the cache base_url=os.environ.get("TYPESAFE_ENDPOINT"), headers={"TypeSafe-Danger-Zone-Images": "true"}, timeout=120.0, ) EXAMPLES = ( "https://raw.githubusercontent.com/typesafe-ai/typesafe-public-examples/pub-20261126-cfe720/" "cookbooks/ocr_confidence_bounding_boxes" ) def download(name: str) -> Path: """Fetch one of this cookbook's files from typesafe-public-examples unless it is on disk.""" path = Path(name) if not path.exists(): path.parent.mkdir(parents=True, exist_ok=True) urllib.request.urlretrieve(f"{EXAMPLES}/{name}", path) return path CACHE = Path("ocr_confidence_bounding_boxes_cache.json") # True fills CACHE with the published answers, so the run makes no requests. To run # live, set it to False and delete CACHE; a CACHE already on disk is never overwritten. DOWNLOAD_CACHE = True if DOWNLOAD_CACHE: download(CACHE.name) json_cache = JsonCache(CACHE) See all 63 lines Load the photos and what the extractor read The two photos are invoices a restaurant received from its suppliers, taken with a phone. One is a creased carbon copy from Milkwood Mushrooms. The other is from Siyakhula Trading and has a shadow down the middle, making it a challenging OCR task. The extracted values are in extractions.json. We used Apple Vision’s text recognition (OCR) to read the photos, and an LLM to read the output of that and return the structured values. Any extractor works here, because the check only needs the photo and the values. INPUTS = Path("inputs") # the photos, keyed in extractions.json by file name EXTRACTIONS = json.loads(download("extractions.json").read_text()) for photo in EXTRACTIONS: download(f"inputs/{photo}") FIELDS = { # field: what it is, in the words every question uses "supplier_name": "the supplier's (seller's) business name", "invoice_number": "the invoice or document number", "invoice_date": "the invoice date", "amount_due": "the final total amount payable", "bank_name": "the name of the supplier's bank in the payment details", "account_holder": "the account holder name in the supplier's bank details", "account_number": "the supplier's bank account number", "branch_code": "the supplier's bank branch code", } SAME_VALUE = "Ignore differences in spacing, punctuation, currency symbols and letter case." for photo, values in sorted(EXTRACTIONS.items()): with PILImage.open(INPUTS / photo) as page: print(f"{photo} ({page.width} x {page.height} px)") for field, value in values.items(): print(f" {field:<16}{value}") milkwood.jpg (1393 x 1080 px) supplier_name MILKWOOD mushrooms invoice_number AN400074 invoice_date 01/09/2026 amount_due 504.70 bank_name Standard Bank account_holder MILKWOOD account_number 080 11 4941 siyakhula.jpg (899 x 1599 px) supplier_name Siyakhula Trading Services (Pty) Ltd ta Siyakhula Trading invoice_number INV03070 invoice_date 16/09/2028 amount_due R1,305.65 bank_name Standard Bank account_holder Siyakhula Trading account_number 10 13 205 260 5 branch_code 051001 Jev accepts images between 280 and 1568 pixels on each side. Larger images are shrunk, and small crops are enlarged so their text is readable. An image that is still too small goes in the middle of a white canvas, and its place on the canvas is kept, so a box Jev draws on the canvas can be converted back to a position on the crop. def as_image(picture: PILImage.Image, upscale_to: int | None = None) -> tuple[Image, tuple]: picture = picture.convert("RGB") if upscale_to and max(picture.size) < upscale_to: scale = upscale_to / max(picture.size) picture = picture.resize( (round(picture.width * scale), round(picture.height * scale)), PILImage.LANCZOS ) picture.thumbnail((MAX_SIDE, MAX_SIDE)) frame = (0.0, 0.0, 1.0, 1.0) # left, top, width, height of the picture on the canvas if min(picture.size) < MIN_SIDE: canvas = PILImage.new("RGB", (max(picture.width, MIN_SIDE), max(picture.height, MIN_SIDE)), "white") x, y = (canvas.width - picture.width) // 2, (canvas.height - picture.height) // 2 canvas.paste(picture, (x, y)) frame = (x / canvas.width, y / canvas.height, picture.width / canvas.width, picture.height / canvas.height) picture = canvas buffer = io.BytesIO() picture.save(buffer, "JPEG", quality=90) return Image(buffer.getvalue()), frame def crop(photo: str, box: dict, pad: float = 0.0) -> PILImage.Image: with PILImage.open(INPUTS / photo) as page: w, h = page.size return page.convert("RGB").crop(( max(0, int((box["left"] - pad) * w)), max(0, int((box["top"] - pad) * h)), min(w, int((box["right"] + pad) * w)), min(h, int((box["bottom"] + pad) * h)), )) Find each field on the page The first of the three requests sends the whole photo, with two questions for each field: A Box question that finds the field. It includes the extracted value as a hint about which text to box. This box decides where to zoom in. A Noul question that asks whether the extracted value is that field on this page. Its P(yes) is the first of the two checks, the page check. def page_questions(values: dict) -> dict: questions = {} for field, value in sorted(values.items()): questions[f"box_{field}"] = Box( instructions=f"{FIELDS[field]}, printed as “{value}” in `page`" ) questions[f"fits_{field}"] = Noul( instructions=f"Is “{value}” {FIELDS[field]} on `page`? {SAME_VALUE}" ) return questions def as_json(questions: dict) -> str: return json.dumps( {key: q.model_dump(mode="json", exclude_none=True) for key, q in questions.items()} ) @json_cache def find_fields(photo: str, questions_json: str, model: str) -> dict: questions = json.loads(questions_json) fields = sorted(key.removeprefix("box_") for key in questions if key.startswith("box_")) with PILImage.open(INPUTS / photo) as page: image, _ = as_image(page) # a whole page fills the size range, so no canvas response = client.system_one( state={"page": image}, questions=questions, model=model ) return { "boxes": {f: response.boxes[f"box_{f}"].box.model_dump() for f in fields}, "fits": {f: response.nouls[f"fits_{f}"].noul for f in fields}, } found = {photo: find_fields(photo, as_json(page_questions(values)), model=TYPESAFE_MODEL) for photo, values in sorted(EXTRACTIONS.items())} for photo, result in found.items(): print(photo) for field, value in EXTRACTIONS[photo].items(): print(f" {field:<16}{value:<24.24} value fits the page {result['fits'][field]:.2f}") See all 39 lines milkwood.jpg supplier_name MILKWOOD mushrooms value fits the page 0.98 invoice_number AN400074 value fits the page 0.88 invoice_date 01/09/2026 value fits the page 0.53 amount_due 504.70 value fits the page 0.95 bank_name Standard Bank value fits the page 0.98 account_holder MILKWOOD value fits the page 0.90 account_number 080 11 4941 value fits the page 0.35 siyakhula.jpg supplier_name Siyakhula Trading Servic value fits the page 0.96 invoice_number INV03070 value fi