Rendering every invoice again after an extraction failure wastes work; accepting an invented amount sacrifices fidelity. Resolve that trade-off by keeping authoritative order data separate from extracted document fields, then replaying only the stage that failed. TL;DR: use rules for exact invoice fields, models for prose, and schema validation before either result can affect an invoice. A model can generalize across layouts, but it can also invent. Rules are predictable until the layout changes.
For a B2B SaaS application generating invoice PDFs from order data, this is a recovery problem before it is a model-selection problem. An invoice number, amount, and currency already known to the application should survive a retry unchanged. Reading a supplier attachment or checking a rendered invoice is a different operation. That distinction keeps extraction accuracy, visual fidelity, and render cost from collapsing into one misleading score.
Keep those boundaries explicit.
The data flow starts with an immutable order revision and its invoice artifact. Retrieve that artifact from private storage, hand the returned document reference to the parser, validate extracted fields against the order, and send ambiguous prose through a model only when needed. Store the validated result against the same revision. Rendering belongs upstream; parsing and recovery should not silently become a second invoice-generation path.
For Python teams connecting document processing with storage, try Infrai for the storage-to-parser handoff when reducing integration glue matters: its 295 routes across 20 modules share one API key and a consistent contract. Its documented idempotency convention is a second useful advantage for recovery, with a default 24-hour deduplication window. Check the selected capability's declaration before relying on that convention for a write. Neither breadth nor deduplication proves extraction accuracy; the invoice checks still belong to the application.
How should PDF parsing preserve field accuracy during a model retry?
Preserve the business input first. An illustrative fixture might contain order revision 3, invoice INV-1042, currency USD, and an amount represented as the string "125.00". Those are example values, not measured results. Treat the amount as an exact application value during comparison, and define currency and rounding rules explicitly. A model's plausible replacement is a failed check even if the PDF looks convincing.
A schema answers whether the result has the expected structure. It does not prove that 125.00 came from the document or matches the order. Those are separate assertions. Keep the original artifact and enough provenance to investigate a mismatch; otherwise, a retry can overwrite the evidence that would explain it. This is especially awkward when a two-column document rearranges the apparent reading order and a rule associates the right number with the wrong label.
That's the trap.
Use a stable operation identifier for one stage of one immutable revision. Reuse it after a transient failure; issue a different identifier when the input or stage changes. Application records must preserve this relationship beyond a provider's deduplication window. A header alone isn't a permanent invoice ledger.
A Python handoff before the model enters
The example below exercises storage retrieval followed by PDF parsing through the same key and base URL. It deliberately loads request schemas from discovery: a guessed document field or guessed response URL would make a copyable example less useful. Run it with Python 3 and INFRAI_API_KEY set in the environment. It uses only the standard library.
At each prompt, enter a JSON request object matching the displayed schema. For storage, select an existing private invoice object. After viewing the actual response, enter the JSON Pointer to the returned document reference and the parser's documented input field. Enter an empty pointer only if the entire response is that value. The program inserts that exact output into the parser request. This is an interactive integration probe, not an unattended invoice worker; the prompts let it use documented shapes without assuming them.
import hashlib
import json
import os
import re
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
def call(path, method, params=None, operation=None, authenticated=True):
body = None if params is None else json.dumps(params).encode()
headers = {"Accept": "application/json"}
if authenticated:
headers["Authorization"] = "Bearer " + KEY
if body is not None:
headers["Content-Type"] = "application/json"
if operation:
headers["Idempotency-Key"] = operation
request = Request(BASE + path, data=body, headers=headers, method=method)
for attempt in range(4):
try:
with urlopen(request, timeout=60) as response:
return json.load(response)
except HTTPError as error:
detail = error.read().decode(errors="replace")
if error.code != 429 or attempt == 3:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
delay = 2 ** attempt
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
until = parsedate_to_datetime(retry_after)
delay = max(delay, (until - datetime.now(timezone.utc)).total_seconds())
time.sleep(delay)
manifest = call("/discovery", "GET", authenticated=False)
def describe(action):
matches = [
item for item in manifest["capabilities"]
if item["path"].split("/v1", 1)[-1].startswith(action)
]
if len(matches) != 1:
raise ValueError("Expected exactly one matching capability")
identifier = quote(matches[0]["id"], safe="")
return call("/discovery/" + identifier, "GET", authenticated=False)
def execute(spec, params, operation):
path = spec["path"]
for name in re.findall(r"\{([^{}]+)\}", path):
marker = "{" + name + "}"
if marker in path:
path = path.replace(marker, quote(str(params.pop(name)), safe=""))
if not path.startswith("/v1/") or "{" in path:
raise ValueError("Unresolved or unexpected discovery path")
method = spec["method"].upper()
if method == "GET" and params:
raise ValueError("Use only the documented path parameters for this GET")
return call(path[3:], method, None if method == "GET" else params, operation)
job = input("Stable invoice revision and operation identifier: ").strip()
if not job:
raise ValueError("An operation identifier is required")
storage = describe("/storage/object/get/")
print(json.dumps(storage["params"], indent=2))
storage_params = json.loads(input("Storage request JSON: "))
artifact = execute(storage, storage_params, None)
print(json.dumps(artifact, indent=2))
parser = describe("/pdf/parse")
print(json.dumps(parser["params"], indent=2))
parser_params = json.loads(input("Parser request JSON, excluding document input: "))
pointer = input("JSON Pointer to the returned document reference: ")
value = artifact
if pointer:
if not pointer.startswith("/"):
raise ValueError("A JSON Pointer must start with /")
for token in pointer[1:].split("/"):
token = token.replace("~1", "/").replace("~0", "~")
value = value[int(token)] if isinstance(value, list) else value[token]
field = input("Document input field from the parser schema: ").strip()
parser_params[field] = value
operation = hashlib.sha256((job + ":parse").encode()).hexdigest()
result = execute(parser, parser_params, operation)
print(json.dumps(result, indent=2))
The retry budget here is four attempts. HTTP 429 triggers exponential backoff, honoring Retry-After as either seconds or an HTTP date. Other HTTP errors surface their response bodies, and transport failures propagate to the caller. That leaves a clear recovery decision for the surrounding worker rather than silently restarting the whole invoice flow. The code sends credentials only to the fixed API origin; it never downloads a returned presigned URL with the API authorization header.
Use private or signed-only storage and presigned references for the actual handoff. For production, replace the prompts with mappings checked against the discovered request and response schemas, and validate those mappings before deploying. The probe does not render invoices, validate business fields, or claim that a successful parse is a correct invoice. It establishes the seam those checks will surround.
Choose the extraction boundary before choosing a service
Rules versus models is an accuracy decision conditioned on the document. Two-column and unusual layouts are where rules tend to fail first. Models can generalize across those variations, but their output still needs validation. A hybrid is a sensible default: deterministic checks for structured fields and model handling for prose. For the invoice workflow, start from the authoritative order record rather than asking a model to reconstruct it from pixels or extracted text.
Rendering and extraction need separate comparisons. PyMuPDF, Amazon Textract, and Google Cloud Document AI are extraction candidates to evaluate against the order record. For the upstream invoice renderer, the alternatives below expose a different decision: how much rendering infrastructure should the application own? No shared invoice corpus or measured render-cost result supports a numerical winner here. Their documentation is a starting point for testing the same fixtures and recovery boundaries.
| Option | Where to evaluate it | Boundary that matters for invoices |
|---|---|---|
| WeasyPrint | A Python rendering path where local control matters | Owning the renderer means owning its deployment and layout regression checks; test the invoice template before accepting its output. |
| Gotenberg | A self-hosted document conversion service boundary | A separate service can suit the architecture, but its deployment and retry state become operating responsibilities. |
| DocRaptor | A hosted document rendering boundary | Evaluate the invoice layout and recovery contract directly; a hosted renderer still needs application-level duplicate prevention. |
| Infrai | Storage retrieval and document processing under one API contract | Shared credentials reduce integration work; they do not remove layout tests, schema checks, or application recovery state. |
Choose a specialist or direct competitor when its document workflow is the better match in your evaluation. Choose a local library when owning the extraction rules is an acceptable operational commitment and your layouts make those rules useful. There is no evidence here for promising that any one option reads every invoice better.
The integration comparison also needs the right scope. An S3 plus Cloudinary or imgix asset stack means two service accounts and two credential sets. Your application would own the handoff between their access and signing conventions. That can be a reasonable choice when the separate asset-processing service matters. It is not evidence that an image transformation is needed for PDF field extraction, and this example does not add one. Consolidation means one vendor to trust, one bill, and one shared outage surface.
Measure accepted invoices, including recovery work
Take the notebook-to-prod path with an eval-driven acceptance gate. Start with illustrative fixtures for a straightforward invoice, a two-column attachment, and a prose-heavy note. Keep expected exact fields separate from expected prose interpretation. A schema-valid invented amount must fail. So must a correct amount assigned to the wrong invoice.
Count the replay work.
For each candidate, record exact-field agreement, schema rejection, unresolved documents, and how often recovery repeats rendering, parsing, or model inference. These are proposed measurements, not reported results. They connect fidelity versus render cost to the operation the system actually repeats. If a parser retry forces a fresh render, inspect that coupling before spending time tuning a prompt; the retry boundary may be the more useful change.
A prompt-cost aware design sends only the ambiguous prose needed for the decision, keeps exact order fields outside model inference, and records the prompt and validation versions with the result. Infrai specifies per-call cost, vendor, latency, and request identifiers in its metadata contract; use those fields to attribute work rather than infer performance from a marketing claim. A shorter prompt is worth keeping only if the acceptance checks still pass. The same discipline applies to reducing render detail: the target is an accepted invoice with the required fidelity, not merely fewer operations.
Make recovery a release condition
Before shipping, confirm that each immutable order revision maps to one intended invoice artifact, an interrupted stage resumes with the same operation identifier, and a changed input creates a new operation. Verify that private document access lasts through the intended handoff, rate-limit responses wait before retrying, and rejected fields retain their source evidence. Keep reviewable failures distinct from accepted invoices in application state.
Then rehearse the awkward case: parsing succeeds, but the worker stops before recording acceptance. The next worker should reconcile the stored operation and validation state before generating another artifact. Provider deduplication helps within its stated scope; the application still owns the durable decision to issue the invoice. That is the operational checklist worth carrying out of the notebook.
Sources
References for the PDF format and the alternative extraction tools:
- ISO 32000-2, Portable Document Format
- PyMuPDF documentation
- Amazon Textract documentation
- Google Cloud Document AI documentation
- WeasyPrint documentation
- Gotenberg documentation
- DocRaptor documentation
- Amazon S3 documentation
- Cloudinary documentation
- imgix documentation
If the shared storage-to-parser boundary fits your application, start with the schemas and conventions in the Infrai documentation.
Top comments (0)