DEV Community

Cover image for Read a Passport MRZ in Python and Verify the Check Digits
AI Engine
AI Engine

Posted on Originally published at ai-engine.net

Read a Passport MRZ in Python and Verify the Check Digits

The two lines of letters, digits and chevrons at the bottom of a passport are the machine readable zone, or MRZ. They hold the holder's name, document number, nationality, birth date and expiry date, plus check digits that prove each field was read correctly. This tutorial shows how to read a passport MRZ in Python: the check digit algorithm in 10 lines, reading the MRZ from a photo, then one API call that returns verified fields and a verdict.

Every script was run on official specimen documents published by governments (Dutch and Norwegian passports, Croatian and Luxembourg ID cards). Specimens carry fictional data and are public domain or CC0 on Wikimedia Commons.

Want to verify ID documents in your app? Get a free key for the ID Document OCR API.


What is in a passport MRZ

Passports use the TD3 format defined by ICAO Doc 9303: two lines of exactly 44 characters. Empty positions are filled with <, which also separates the last name from the first names.

The MRZ of the Dutch specimen passport with each field and the four check digits outlined

Dates are written YYMMDD, so 650310 is March 10, 1965. Four digits protect the data: after the document number, after the birth date, after the expiry date, and a composite digit covering the whole second line.


The check digit algorithm in 10 lines of Python

Digits keep their value, A to Z are 10 to 35, the filler is 0. Multiply by the weights 7, 3, 1 repeated and keep the sum modulo 10. Save this as mrz.py:

WEIGHTS = (7, 3, 1)


def char_value(c):
    if c.isdigit():
        return int(c)
    if c.isalpha():
        return ord(c.upper()) - 55  # A=10 ... Z=35
    return 0  # the filler '<'


def check_digit(data):
    """ICAO 9303 check digit: weights 7, 3, 1 repeated, sum modulo 10."""
    return str(sum(char_value(c) * WEIGHTS[i % 3] for i, c in enumerate(data)) % 10)


def parse_td3(line1, line2):
    """Parse the two 44-character lines of a passport MRZ and verify every check digit."""
    surname, _, given = line1[5:].partition("<<")
    fields = {
        "country": line1[2:5].replace("<", ""),
        "last_name": surname.replace("<", " ").strip(),
        "first_name": given.replace("<", " ").strip(),
        "document_number": line2[0:9].replace("<", ""),
        "nationality": line2[10:13].replace("<", ""),
        "birth_date": line2[13:19],
        "sex": line2[20],
        "expiry_date": line2[21:27],
    }
    checks = {
        "document_number": check_digit(line2[0:9]) == line2[9],
        "birth_date": check_digit(line2[13:19]) == line2[19],
        "expiry_date": check_digit(line2[21:27]) == line2[27],
        "composite": check_digit(line2[0:10] + line2[13:20] + line2[21:43]) == line2[43],
    }
    return fields, checks


if __name__ == "__main__":
    line1 = "P<NLDDE<BRUIJN<<WILLEKE<LISELOTTE<<<<<<<<<<<"
    line2 = "SPECI20142NLD6503101F2403096999999990<<<<<84"
    fields, checks = parse_td3(line1, line2)
    print(fields)
    print(checks)

    # One digit changed: birth year 1965 -> 1968
    tampered = line2[:14] + "8" + line2[15:]
    print(parse_td3(line1, tampered)[1])
Enter fullscreen mode Exit fullscreen mode
{'country': 'NLD', 'last_name': 'DE BRUIJN', 'first_name': 'WILLEKE LISELOTTE', 'document_number': 'SPECI2014', 'nationality': 'NLD', 'birth_date': '650310', 'sex': 'F', 'expiry_date': '240309'}
{'document_number': True, 'birth_date': True, 'expiry_date': True, 'composite': True}
{'document_number': True, 'birth_date': False, 'expiry_date': True, 'composite': False}
Enter fullscreen mode Exit fullscreen mode

Change one digit of the birth year and two checks fail: the birth date digit and the composite digit. An OCR engine that confuses 5 and 6, or O and 0, cannot produce a wrong value that still passes, except by rare chance.


Read the MRZ from a photo

With the OCR Wizard API, keep the lines that are 44 characters long and contain a filler, after removing spaces. Save this next to mrz.py as ocr_mrz.py:

import os
import sys

import requests

from mrz import parse_td3

HOST = "ocr-wizard.p.rapidapi.com"
HEADERS = {"x-rapidapi-host": HOST, "x-rapidapi-key": os.environ["RAPIDAPI_KEY"]}


def read_mrz_lines(path):
    """OCR the photo and keep the two passport MRZ lines (44 characters, with fillers)."""
    with open(path, "rb") as f:
        r = requests.post(f"https://{HOST}/ocr", headers=HEADERS, files={"image": f}, timeout=60)
    r.raise_for_status()
    lines = [l.replace(" ", "") for l in r.json()["body"]["fullText"].split("\n")]
    mrz = [l for l in lines if len(l) == 44 and "<" in l]
    if len(mrz) != 2:
        raise ValueError(f"MRZ not found in {path}")
    return mrz


for path in sys.argv[1:]:
    line1, line2 = read_mrz_lines(path)
    fields, checks = parse_td3(line1, line2)
    print(path, "all checks pass" if all(checks.values()) else checks)
    print(" ", fields)
Enter fullscreen mode Exit fullscreen mode
nl_passport.jpg all checks pass
  {'country': 'NLD', 'last_name': 'DE BRUIJN', 'first_name': 'WILLEKE LISELOTTE', 'document_number': 'SPECI2014', 'nationality': 'NLD', 'birth_date': '650310', 'sex': 'F', 'expiry_date': '240309'}
no_passport.jpg all checks pass
  {'country': 'NOR', 'last_name': 'OESTENBYEN', 'first_name': 'AASAMUND SPECIMEN', 'document_number': 'CCC002251', 'nationality': 'NOR', 'birth_date': '560423', 'sex': 'M', 'expiry_date': '300415'}
Enter fullscreen mode Exit fullscreen mode

Notice OESTENBYEN: the printed name is Østenbyen, and the MRZ only allows A to Z, so ICAO transliterates Ø to OE.

A production KYC flow quickly needs more: ID cards (TD1, three lines of 30) and permits (TD2), the printed zone compared with the MRZ, national numbers with their own checksums, driving licenses without an MRZ, several phone photos in any order, and a clear decision.


Verify any ID document with one API call

The ID Document OCR API does all of that in one request to /parse-id: 1 to 6 images or a PDF in, every field in ISO format with a trust level, each check result, and a verdict (ok, review or rejected). This script runs it on five documents, including three simulated phone shots of the Norwegian passport and the Dutch passport with its birth year edited:

import os
import time

import requests

HOST = "id-document-ocr-verification.p.rapidapi.com"
HEADERS = {"x-rapidapi-host": HOST, "x-rapidapi-key": os.environ["RAPIDAPI_KEY"]}


def verify_id(*paths):
    """Send one document (1 to 6 photos, any order) and return the parsed result."""
    files = [("images", open(p, "rb")) for p in paths]
    try:
        r = requests.post(f"https://{HOST}/parse-id", headers=HEADERS, files=files, timeout=60)
    finally:
        for _, f in files:
            f.close()
    r.raise_for_status()
    return r.json()["result"]


def decide(result):
    """Automate only what the checksums back, send the rest to a person."""
    verdict = result["verdict"]
    if verdict["status"] == "ok" and not verdict["is_expired"]:
        return "accept"
    if verdict["status"] == "ok":
        return "ask for a valid document (expired)"
    failed = [name for name, passed in verdict["mrz_checks"].items() if not passed]
    reasons = failed + verdict["mismatched_fields"] + verdict["missing_critical_fields"]
    return f"{verdict['status']}: {', '.join(reasons)}"


DOCUMENTS = {
    "Dutch passport": ["nl_passport.jpg"],
    "Norwegian passport, 3 phone shots": ["phone/no_shot1.jpg", "phone/no_shot2.jpg", "phone/no_shot3.jpg"],
    "Croatian ID card": ["hr_id.jpg"],
    "Luxembourg ID card, back": ["lu_id_back.jpg"],
    "Dutch passport, birth year edited": ["nl_passport_tampered.jpg"],
}

for name, paths in DOCUMENTS.items():
    start = time.time()
    result = verify_id(*paths)
    f = result["fields"]
    print(f"{name} ({time.time() - start:.1f} s)")
    print(f"  {result['document_type']} {result['country']} | {f['last_name']['value']}, "
          f"{f['first_name']['value']} | born {f['birth_date']['value']} | "
          f"expires {f['expiry_date']['value']}")
    print(f"  -> {decide(result)}")
Enter fullscreen mode Exit fullscreen mode
Dutch passport (1.7 s)
  passport NLD | DE BRUIJN, WILLEKE LISELOTTE | born 1965-03-10 | expires 2024-03-09
  -> ask for a valid document (expired)
Norwegian passport, 3 phone shots (1.5 s)
  passport NOR | OESTENBYEN, AASAMUND SPECIMEN | born 1956-04-23 | expires 2030-04-15
  -> accept
Croatian ID card (1.1 s)
  id_card HRV | SPECIMEN, SPECIMEN | born 1977-01-01 | expires 2002-12-12
  -> ask for a valid document (expired)
Luxembourg ID card, back (0.7 s)
  id_card LUX | SPECIMEN, JEANNE | born 1983-08-19 | expires 2031-07-15
  -> accept
Dutch passport, birth year edited (2.3 s)
  passport NLD | DE BRUIJN, WILLEKE LISELOTTE | born 1968-03-10 | expires 2024-03-09
  -> review: birth_date, composite
Enter fullscreen mode Exit fullscreen mode

Five specimen documents with the decision for each: expired, accepted, or sent to review

  • Expired but authentic: the Dutch passport and Croatian ID card pass every check, with is_expired: true as a separate flag.
  • Three phone shots, one answer: grouped, voted field by field, one result in 1.5 seconds.
  • ID card back only: the Luxembourg card is read from its TD1 MRZ.
  • Edited birth year: the birth date and composite checks fail, verdict review, same as our own mrz.py.

Read the verdict and field status

On the edited passport, the fields covered by the failed checks are marked mrz_unchecked:

{
  "birth_date": {
    "value": "1968-03-10",
    "status": "mrz_unchecked"
  },
  "last_name": {
    "value": "DE BRUIJN",
    "status": "mrz_unchecked"
  },
  "verdict": {
    "status": "review",
    "is_expired": true,
    "mrz_checks": {
      "document_number": true,
      "birth_date": false,
      "expiry_date": true,
      "composite": false
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  • ok: every critical field extracted, every check passed. Safe to automate.
  • review: a check failed, a field is missing, or the MRZ and the printed zone disagree. Send to a person.
  • rejected: the MRZ fails several integrity checks.

Production tips

  • Ask for 2 or 3 photos of each side so the vote picks the best reading of each field.
  • Treat expiry as a business rule: an expired passport is still authentic.
  • Do not store the images once the fields are verified. The API keeps nothing.
  • Match the face too: compare a selfie with the document photo, as in the selfie to ID verification tutorial.

Full tutorial with images: Read a Passport MRZ in Python on ai-engine.net.


Get a free key on the ID Document OCR API page, save verify_id.py and run it on a specimen.

Sources: ICAO Doc 9303. Specimens on Wikimedia Commons: Dutch passport, Norwegian passport, Croatian ID card, Luxembourg ID card.

Top comments (0)