Dev.to Security 🔐 Cybersecurity 👁 0 📖 6 min read

Age Verification in Python: Face Estimate First, ID Document as Proof

Age checks sit in front of alcohol delivery, vape shops, betting, dating and adult content, and they all face the same trade-off. A face estimate is fast and needs nothing from the user, but it gives a range, not a proof

Age Verification in Python: Face Estimate First, ID Document as Proof

Age checks sit in front of alcohol delivery, vape shops, betting, dating and adult content, and they all face the same trade-off. A face estimate is fast and needs nothing from the user, but it gives a range, not a proof. An ID document gives an exact birth date, but asking every visitor for one loses customers. This tutorial builds an age verification flow in Python that uses both: a selfie first, an ID document only when the face is too close to call.

It uses two APIs: the Face Analyzer API to estimate age from a selfie, and the ID Document OCR API to read and verify the birth date on a passport or ID card. Every result below comes from a live call, on free stock portraits and official specimen documents.

Face estimate or ID document: what each one proves

  • Face estimate: an age range from a selfie, best for clear cases far from the limit. It does not prove an exact age.
  • ID document: an exact birth date checked against the MRZ, best for close cases and regulated checks. It does not prove that the document belongs to the person.

The two cover each other. The face settles the clear cases without friction, the document settles the close ones, and the face also tells you when a document does not fit the person sending it.

The script

One file, three steps: estimate_age reads the face, age_from_id reads and verifies the birth date, and verify_age decides. Set your key in RAPIDAPI_KEY and install requests.

import os
from datetime import date

import requests

KEY = os.environ["RAPIDAPI_KEY"]
FACE_HOST = "faceanalyzer-ai.p.rapidapi.com"
ID_HOST = "id-document-ocr-verification.p.rapidapi.com"


def headers(host):
    return {"x-rapidapi-key": KEY, "x-rapidapi-host": host}


def estimate_age(selfie):
    """Age range of the single face in a selfie, or None."""
    with open(selfie, "rb") as f:
        r = requests.post(f"https://{FACE_HOST}/faceanalysis",
                          headers=headers(FACE_HOST), files={"image": f}, timeout=30)
    r.raise_for_status()
    faces = r.json()["body"]["faces"]
    if len(faces) != 1:
        return None
    return faces[0]["facialFeatures"]["AgeRange"]


def age_on(birth, today):
    """Exact age in years, birthday not reached yet counts one year less."""
    before_birthday = (today.month, today.day) < (birth.month, birth.day)
    return today.year - birth.year - before_birthday


def age_from_id(*paths, today=None, accept_expired=True):
    """Return (age, reason). age is None when the birth date can't be trusted."""
    files = [("images", open(p, "rb")) for p in paths]
    r = requests.post(f"https://{ID_HOST}/parse-id",
                      headers=headers(ID_HOST), files=files, timeout=60)
    r.raise_for_status()
    result = r.json()["result"]
    verdict = result["verdict"]

    if verdict["status"] != "ok":
        failed = [k for k, ok in verdict["mrz_checks"].items() if not ok]
        return None, f"document {verdict['status']}: " + ", ".join(
            failed + verdict["mismatched_fields"] + verdict["missing_critical_fields"])
    if verdict["is_expired"] and not accept_expired:
        return None, "document expired"
    birth = result["fields"].get("birth_date", {})
    if birth.get("status") in (None, "missing"):
        return None, "no birth date on the document"

    age = age_on(date.fromisoformat(birth["value"]), today or date.today())
    return age, f"born {birth['value']} ({birth['status']})"


def verify_age(selfie, id_paths=(), min_age=18, buffer=7):
    """Face estimate first, ID document only when the face is too close to call."""
    face = estimate_age(selfie) if selfie else None
    if face and face["Low"] >= min_age + buffer:
        return "pass", f"face {face['Low']}-{face['High']}"
    if not id_paths:
        return "ask_for_id", f"face {face['Low']}-{face['High']}" if face else "no single face"

    age, reason = age_from_id(*id_paths)
    if age is None:
        return "manual_review", reason
    if face and not face["Low"] - 10 <= age <= face["High"] + 10:
        return "manual_review", f"ID age {age} does not fit face {face['Low']}-{face['High']}"
    return ("pass" if age >= min_age else "deny"), f"ID age {age}, {reason}"


if __name__ == "__main__":
    import sys
    selfie, *ids = sys.argv[1:]
    decision, reason = verify_age(selfie, ids)
    print(f"{decision:14} {reason}")

The rule is 18 or over, with a 7-year buffer on the face: a selfie passes alone only when the lowest age of its range is 25 or more. Change min_age to 21 for alcohol in the United States.

Read and verify the birth date

/parse-id returns each field with a status, plus a verdict. The script uses the birth date only when the verdict is ok: every MRZ check digit passed and the printed text did not contradict it. On three specimens it returned 70 (Norwegian passport), 49 (Croatian ID card) and 61 (Dutch passport). Two of them are expired; accept_expired=True keeps them, since an expired document still proves a birth date. Set it to False where the law asks for a valid document.

A person is 18 on their 18th birthday, not on January 1, and the tuple comparison in age_on gets every case right, including February 29:

>>> age_on(date(2008, 11, 28), date(2026, 11, 27))  # birthday tomorrow
17
>>> age_on(date(2008, 11, 27), date(2026, 11, 27))  # birthday today
18
>>> age_on(date(2008, 2, 29), date(2026, 2, 28))    # leap day, not yet
17
>>> age_on(date(2008, 2, 29), date(2026, 3, 1))
18

Decide, on real photos

$ python age_check.py selfie_1.jpg
pass           face 78-86
$ python age_check.py selfie_2.jpg
ask_for_id     face 23-29
$ python age_check.py selfie_4.jpg
ask_for_id     face 19-25
$ python age_check.py selfie_3.jpg croatian_id.jpg
manual_review  ID age 49 does not fit face 13-21
$ python age_check.py selfie_4.jpg passport_edited.jpg
manual_review  document review: composite

Five verify_age results: one face passes, two are asked for an ID, a borrowed ID and an edited passport go to manual review

The first selfie passes in one call, under a second. The next two are adults by their looks, but the low end of their range is under 25, so the app asks for a document instead of guessing.

A borrowed ID: the age does not fit the face

An ID check alone proves the age of the document, not of the person. We sent a selfie estimated 13 to 21 with the Croatian specimen card, whose holder is 49. The document is authentic, so age_from_id returns 49. The consistency line catches it: an ID age more than 10 years outside the face range goes to review. For regulated checks, add a real face comparison between the selfie and the ID photo, as in the selfie to ID verification tutorial.

An edited birth date: the check digits disagree

We changed the birth year on a copy of the Dutch specimen passport from 1965 to 1999. With the year alone changed, the birth_date and composite checks fail. With its check digit recalculated too, the composite check still fails, because it covers the document number, birth date and expiry date together. Both come back as review and the flow sends them to a person. More edits in the fake ID detection tutorial.

Production tips

  • Keep the rule in config: min_age, the buffer, the 10-year tolerance and accept_expired depend on your country and product.
  • Do not tell the user why a check failed: a precise error turns your app into a testing tool for edited documents.
  • Store the decision, not the documents: keep the result, the date and the reason, and delete the images.
  • Ask for a better photo before a person looks: the ID API accepts several photos of the same side in one call and votes field by field.

Full tutorial with images: Age Verification in Python on ai-engine.net.

Next step

Get a key for the Face Analyzer API and the ID Document OCR API, save age_check.py and run it on a selfie. Then add a specimen passport and set min_age to your own limit.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.