Blog How to No. 09

Reading purchase orders with Python and the VioPO API

This guide reads a folder of purchase order PDFs with the VioPO API and writes the lines to a CSV file ready to import. It uses only the requests library.

VioPO is not open yet, so this guide is for planning an integration now. Once it opens, you need a VioPO account and an API key from the account page; join the waitlist to hear when accounts open. Put the key in an environment variable rather than in the script:

Bash
export VIOPO_KEY=vpo_live_...
pip install requests

Read one order

read_one.pyPython
import os
import requests

API = "https://viopo.co.uk/v1/extract"
KEY = os.environ["VIOPO_KEY"]

def read_order(path):
    with open(path, "rb") as f:
        r = requests.post(
            API,
            headers={"Authorization": f"Bearer {KEY}"},
            files={"file": (os.path.basename(path), f)},
            timeout=300,
        )
    if r.status_code != 200:
        # A few answers come from the web server in front of the API, as a page, not JSON.
        if "application/json" not in r.headers.get("Content-Type", ""):
            raise RuntimeError(f"{path}: HTTP {r.status_code} from the web server")
        error = r.json()["error"]
        raise RuntimeError(f"{path}: {error['code']}: {error['message']}")
    return r.json()

result = read_order("order.pdf")
order = result["data"]
print(order["header"]["po_number"], order["header"]["po_date"], order["totals"]["total"])

Reading takes 20 to 40 seconds for a one page order, so the timeout is generous.

Handle the errors worth handling

These errors are worth treating differently from the rest:

  • 503 busy: every model slot is in use. Wait for the number of seconds in the Retry-After header and try again. A 503 without JSON means the API is restarting, and the same wait works.
  • 429 too_many_in_flight: your account already has as many documents being read as its plan allows. Wait for the seconds in Retry-After, then try again.
  • 502 model_error and 500 server_error: send the file again once or twice. If it keeps failing, check that the file opens normally.
  • 402 quota_exceeded: your pages for the period are used up. Stop, rather than retrying.
retry.pyPython
import time

def read_with_retry(path, attempts=4):
    failures = 0
    for attempt in range(attempts):
        with open(path, "rb") as f:
            r = requests.post(API, headers={"Authorization": f"Bearer {KEY}"},
                              files={"file": f}, timeout=300)
        if r.status_code in (429, 503):
            wait = int(r.headers.get("Retry-After", "30"))
            time.sleep(wait)
            continue
        if "application/json" not in r.headers.get("Content-Type", ""):
            raise RuntimeError(f"{path}: HTTP {r.status_code} from the web server")
        body = r.json()
        # A model or server error is worth two more tries, no more.
        if r.status_code in (500, 502) and failures < 2:
            failures += 1
            time.sleep(10)
            continue
        if r.status_code == 402:
            raise SystemExit(f"Out of pages: {body['error']['message']}")
        if r.status_code != 200:
            raise RuntimeError(f"{path}: {body['error']['code']}: {body['error']['message']}")
        return body
    raise RuntimeError(f"{path}: no result after {attempts} attempts")

You are not charged for a request that fails.

Decide what needs a person

Each result has checks and warnings. A good default is to pass an order through only when every check passed and there are no warnings:

Python
def needs_review(order):
    failed = [c["detail"] for c in order["checks"] if not c["passed"]]
    if not order["checks"]:
        failed.append("No figures could be checked.")
    return failed + order["warnings"]

An empty list means the figures on the order agree with each other and nothing was left unread. An order with no checks at all goes to review too: when no prices or totals could be read, there was nothing to check.

Write the lines to CSV

to_csv.pyPython
import csv
import glob

FIELDS = ["file", "po_number", "po_date", "currency", "line", "part", "description",
          "quantity", "unit", "unit_price", "line_total", "review"]

with open("orders.csv", "w", newline="") as out:
    w = csv.DictWriter(out, fieldnames=FIELDS)
    w.writeheader()
    for path in sorted(glob.glob("inbox/*.pdf")):
        order = read_with_retry(path)["data"]
        h = order["header"]
        review = "; ".join(needs_review(order))
        for line in order["lines"]:
            w.writerow({
                "file": path,
                "po_number": h["po_number"],
                "po_date": h["po_date"],
                "currency": h["currency"],
                "line": line["line_number"],
                "part": line["buyer_part_number"] or line["supplier_part_number"],
                "description": line["description"],
                "quantity": line["quantity"],
                "unit": line["unit_of_measure"],
                "unit_price": line["unit_price"],
                "line_total": line["line_total"],
                "review": review,
            })
        print(path, "needs review" if review else "ok")

Long documents

For orders of many pages, send them asynchronously with ?async=true and poll GET /v1/extractions/{id} until the status is no longer processing. Then check for failed: a failed job carries an error and is not charged. The docs show the responses.

Check your usage

Python
r = requests.get("https://viopo.co.uk/v1/usage", headers={"Authorization": f"Bearer {KEY}"})
r.raise_for_status()
print(r.json()["pages_remaining"], "pages left this period")

That is the whole integration. From here, the usual next step is to replace the CSV with your ERP's import API, and add a lookup from the customer's part numbers to yours.