DEV Community

Cover image for Driving Licence OCR in Python: Read and Check EU Licences for Car Rental
AI Engine
AI Engine

Posted on Originally published at ai-engine.net

Driving Licence OCR in Python: Read and Check EU Licences for Car Rental

A car rental desk, a van sharing app, a delivery platform signing up couriers: all of them need the same thing from a driving licence. Who is the driver, how old are they, can they drive this vehicle, and is the licence still valid when the car comes back. This tutorial reads EU driving licences with an API in Python and turns those questions into one function that returns ok, review or deny.

It uses the ID Document OCR API, which reads ID cards, passports, residence permits and driving licences. Every result below is a live call on official specimen licences from six countries.


One layout for every EU licence

Every EU member state, plus Norway, Iceland and Liechtenstein, prints the same numbered fields on the same card format. The language changes, the numbers do not:

  • 1 and 2: surname and first names (last_name, first_name)
  • 3: date and place of birth (birth_date)
  • 4a and 4b: issue and expiry dates (issue_date, expiry_date)
  • 4c and 4d: issuing authority and, in some countries, a personal number (authority, personal_number)
  • 5: licence number (document_number)
  • 9: vehicle categories (license_categories)

Polish specimen licence with fields 1, 2, 3, 4a, 4b and 9 mapped to the API result

A licence has no machine-readable zone. Passports carry MRZ lines with check digits (see the passport MRZ tutorial), but on a licence the fields come from the printed card, with the status visual_only. The checks that make a licence safe to accept are rules about dates and categories, and they belong in your code.


The script

parse_licence calls the API, categories turns field 9 into a set of codes, and check_rental decides. Set your key in RAPIDAPI_KEY and install requests.

import os
import re
from datetime import date

import requests

KEY = os.environ["RAPIDAPI_KEY"]
HOST = "id-document-ocr-verification.p.rapidapi.com"

# EU categories, longest first so "C1E" is not read as "C" + "1E"
CODES = ["C1E", "D1E", "AM", "A1", "A2", "B1", "BE", "C1", "CE", "D1", "DE",
         "A", "B", "C", "D", "T"]
# a higher category includes lower ones: BE needs B, C1E needs C1
INCLUDES = {"A": "A2", "A2": "A1", "A1": "AM", "B": "AM", "BE": "B",
            "C1": "B", "C": "C1", "C1E": "C1", "CE": "C", "D1": "B", "D": "D1",
            "D1E": "D1", "DE": "D"}


def parse_licence(*paths):
    """Send one or both sides of a licence, return the API result."""
    files = [("images", open(p, "rb")) for p in paths]
    r = requests.post(f"https://{HOST}/parse-id",
                      headers={"x-rapidapi-key": KEY, "x-rapidapi-host": HOST},
                      files=files, timeout=60)
    r.raise_for_status()
    return r.json()["result"]


def categories(raw):
    """Field 9 as a set of codes: 'AM / B', 'A BE C1E', 'ABC' all work."""
    found = set()
    for token in re.split(r"[\s/,;]+", (raw or "").upper()):
        while token:
            code = next((c for c in CODES if token.startswith(c)), None)
            if code is None:
                break
            found.add(code)
            token = token[len(code):]
    for code in list(found):
        while code in INCLUDES:
            code = INCLUDES[code]
            found.add(code)
    return found


def age_on(birth, day):
    return day.year - birth.year - ((day.month, day.day) < (birth.month, birth.day))


def value(result, name):
    v = result["fields"].get(name, {}).get("value")
    return date.fromisoformat(v) if v and name.endswith("_date") else v


def check_rental(result, return_day, today=None, min_age=21, need="B"):
    """Return (decision, reasons) for one rental: ok, review or deny."""
    today = today or date.today()
    if result["document_type"] != "driving_license":
        return "review", ["not a driving licence"]

    birth, issued = value(result, "birth_date"), value(result, "issue_date")
    expiry = value(result, "expiry_date")
    held = categories(value(result, "license_categories"))
    deny, review = [], []

    if birth is None:
        review.append("no birth date")
    elif age_on(birth, today) < min_age:
        deny.append(f"driver is {age_on(birth, today)}, minimum {min_age}")
    if not held:
        review.append("categories not read")
    elif need not in held:
        deny.append(f"category {need} missing (has {', '.join(sorted(held))})")

    if expiry is None:
        review.append("no expiry date printed (pre-2013 card?)")
    elif expiry < today:
        deny.append(f"expired {expiry}")
    elif expiry < return_day:
        deny.append(f"expires {expiry}, before the car is back")

    if birth and issued and age_on(birth, issued) < 17:
        review.append(f"issued at age {age_on(birth, issued)}")
    if issued and issued > today:
        review.append("issue date in the future")
    if issued and expiry and (expiry - issued).days > 15 * 366:
        review.append("valid for more than 15 years")

    if deny:
        return "deny", deny
    if review:
        return "review", review
    return "ok", [f"age {age_on(birth, today)}, {need} held, valid to {expiry}"]


if __name__ == "__main__":
    import sys
    return_day = date.fromisoformat(sys.argv[1])
    result = parse_licence(*sys.argv[2:])
    decision, reasons = check_rental(result, return_day)
    print(f"{decision:7}", "; ".join(reasons))
Enter fullscreen mode Exit fullscreen mode

The default rule is a rental car: driver 21 or older, category B, licence valid until the return date. Anything that cannot be decided from the card goes to review instead of deny, so a person looks before you turn a customer away.


Read the licence

/parse-id takes the front alone, or front and back together, in the images field. On the Polish specimen:

lic = parse_licence("poland.png")
for k in ["last_name", "first_name", "birth_date", "issue_date",
          "expiry_date", "license_categories"]:
    print(f"{k:19} {lic['fields'][k]['value']:12} {lic['fields'][k]['status']}")
Enter fullscreen mode Exit fullscreen mode
last_name           KOWALSKI     visual_only
first_name          JAN          visual_only
birth_date          1964-04-07   visual_only
issue_date          2019-03-06   visual_only
expiry_date         2028-01-18   visual_only
license_categories  A / B        visual_only
Enter fullscreen mode Exit fullscreen mode

Dates come back in ISO format whatever the country prints, so date.fromisoformat reads them directly. document_type is driving_license, the first thing check_rental tests.


Turn field 9 into categories

Field 9 is printed differently everywhere: A/B in Poland, AM, A, B in Greece, ABC in Finland, codes in boxes in Germany. categories reads the longest code first, so C1E is one category, ignores anything else, and adds the categories a licence includes without printing them: BE means B, C1 requires B. A van over 3.5 tonnes needs C1:

back = date(2026, 12, 5)
for paths in [("norway_front.jpg", "norway_back.png"), ("poland.png",)]:
    lic = parse_licence(*paths)
    print(paths[0], check_rental(lic, back, need="C1"))
Enter fullscreen mode Exit fullscreen mode
norway_front.jpg ('ok', ['age 54, C1 held, valid to 2033-09-01'])
poland.png ('deny', ['category C1 missing (has A, A1, A2, AM, B)'])
Enter fullscreen mode Exit fullscreen mode

Decide, on six countries

For a car returned on December 5, 2026, then the Polish licence again for a car returned in February 2028:

$ python licence_check.py 2026-12-05 poland.png
ok      age 62, B held, valid to 2028-01-18
$ python licence_check.py 2026-12-05 greece.jpg
ok      age 51, B held, valid to 2029-02-18
$ python licence_check.py 2026-12-05 norway_front.jpg norway_back.png
ok      age 54, B held, valid to 2033-09-01
$ python licence_check.py 2026-12-05 germany_2013.jpg
ok      age 62, B held, valid to 2030-01-21
$ python licence_check.py 2026-12-05 italy.jpg
deny    expired 2025-01-01
$ python licence_check.py 2026-12-05 germany_1999.jpg
review  no expiry date printed (pre-2013 card?)
$ python licence_check.py 2026-12-05 romania.jpg
deny    expired 2018-06-10
$ python licence_check.py 2028-02-01 poland.png
deny    expires 2028-01-18, before the car is back
Enter fullscreen mode Exit fullscreen mode

Four licences pass, two expired specimens are denied, and the long rental is denied because the licence expires before the car is back.


Licences with no expiry date

The 1999 German specimen has a dash in field 4b. German licences issued before 19 January 2013 were valid for life, and EU law requires them to be replaced by 19 January 2033, so they are still valid today. check_rental sends them to review. If you accept them, write the rule: Germany, issued before 2013, no expiry, ok until 2033. Note that 4a is the date of this card, not of the driving test.


Romanian licences: the personal number checks itself

Romania prints the CNP in field 4d, a 13-digit number that encodes sex and birth date and ends with a check digit. The API verifies it:

>>> lic = parse_licence("romania.jpg")
>>> lic["verdict"]["national_checks"]
{'rou_cnp': True}
>>> lic["fields"]["birth_date"]
{'value': '1989-03-06', 'status': 'derived_from_document_number'}
Enter fullscreen mode Exit fullscreen mode

The birth date is derived from a number whose checksum passed, which the API documentation ranks as high trust.


Production tips

  • Ask for both sides: the back lists each category with the date it was first obtained, the right date for "licence held for two years" rules.
  • Keep the rules in config: minimum age, required category and accepted countries change by market and vehicle.
  • Show the customer a short message and keep the detailed reason for your staff.
  • Store the decision, not the image: the ID Document OCR API does not store the images you send.
  • Ask for a better photo first when a field is missing: several photos of the same side can go in one call.

Full tutorial with the driver platform re-check and sources: Driving Licence OCR in Python on ai-engine.net.


Next step

Get a key on the ID Document OCR API page, save licence_check.py and run it on a specimen licence. Then set min_age and need to your own rules.

Top comments (0)