mrz-checkdigit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ tags: ["v*"]
7
+ pull_request:
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.10", "3.14"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - run: pip install . pytest
21
+ - run: pytest -q
22
+ - run: mrz-checkdigit 'P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<' 'L898902C36UTO7408122F1204159ZE184226B<<<<<10'
23
+
24
+ publish:
25
+ if: startsWith(github.ref, 'refs/tags/v')
26
+ needs: test
27
+ runs-on: ubuntu-latest
28
+ environment:
29
+ name: pypi
30
+ url: https://pypi.org/p/mrz-checkdigit
31
+ permissions:
32
+ id-token: write
33
+ steps:
34
+ - uses: actions/checkout@v4
35
+ - uses: actions/setup-python@v5
36
+ with:
37
+ python-version: "3.14"
38
+ - run: pip install build && python -m build
39
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,5 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ .venv/
5
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ali Ahmed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.5
2
+ Name: mrz-checkdigit
3
+ Version: 0.1.0
4
+ Summary: Validate passport and ID card MRZ check digits (ICAO 9303: TD1, TD2, TD3)
5
+ Project-URL: Homepage, https://aliahmed.si/
6
+ Project-URL: Documentation, https://aliahmed.si/blog/passport-mrz-check-digits/
7
+ Project-URL: Source, https://github.com/QuantumBreakz/mrz-checkdigit
8
+ Project-URL: Issues, https://github.com/QuantumBreakz/mrz-checkdigit/issues
9
+ Author: Ali Ahmed
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: check-digit,icao,icao-9303,id-card,kyc,mrz,ocr,passport
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+
22
+ # mrz-checkdigit
23
+
24
+ Validate the check digits in a passport or ID card **machine-readable zone (MRZ)**, as defined by ICAO Document 9303. Supports all three layouts:
25
+
26
+ | Layout | Used on | Shape |
27
+ | ------ | ------------------------ | ------------------ |
28
+ | TD1 | ID cards | 3 lines × 30 chars |
29
+ | TD2 | Older ID cards, visas | 2 lines × 36 chars |
30
+ | TD3 | Passports | 2 lines × 44 chars |
31
+
32
+ It checks the document number, date of birth and expiry date digits, the TD3 optional-data digit, and the composite digit. Pure Python, no dependencies, typed.
33
+
34
+ Use it after OCR to reject or retry a misread MRZ (`0`/`O`, `8`/`B`, `1`/`I` and similar) before it reaches your database.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install mrz-checkdigit
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ from mrz_checkdigit import check_digit, is_valid, validate
46
+
47
+ mrz = [
48
+ "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<",
49
+ "L898902C36UTO7408122F1204159ZE184226B<<<<<10",
50
+ ]
51
+
52
+ is_valid(mrz) # True
53
+ check_digit("L898902C3") # 6
54
+
55
+ for r in validate(mrz):
56
+ print(r.field, r.expected, r.computed, r.ok)
57
+ # document_number 6 6 True
58
+ # birth_date 2 2 True
59
+ # expiry_date 9 9 True
60
+ # optional_data 1 1 True
61
+ # composite 0 0 True
62
+ ```
63
+
64
+ The layout is detected from the number and length of the lines. `validate` raises `ValueError` for any other shape.
65
+
66
+ ### Command line
67
+
68
+ ```bash
69
+ mrz-checkdigit 'P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<' 'L898902C36UTO7408122F1204159ZE184226B<<<<<10'
70
+ ```
71
+
72
+ Lines can also be piped on stdin. Exit code is `0` when every digit matches, `1` when one fails, `2` for an unrecognised layout.
73
+
74
+ ## The algorithm
75
+
76
+ Each character becomes a number (digits keep their value, `A`–`Z` = 10–35, `<` = 0), is multiplied by the repeating weights 7, 3, 1, and the check digit is the sum modulo 10.
77
+
78
+ ## Background
79
+
80
+ The full walkthrough, with the field positions, the composite digit and why OCR pipelines depend on it: [How passport MRZ check digits work, with code to validate them](https://aliahmed.si/blog/passport-mrz-check-digits/).
81
+
82
+ Check digits catch accidental errors. They are not a security feature: anyone can compute valid digits. Proving a document is genuine takes authenticity checks or reading the signed NFC chip.
83
+
84
+ ## Limitations
85
+
86
+ - TD1 document numbers longer than 9 characters (the overflow into the optional field) are not handled yet.
87
+ - Only check digits are validated; field formats (dates, country codes) are not.
88
+
89
+ ## License
90
+
91
+ MIT
@@ -0,0 +1,70 @@
1
+ # mrz-checkdigit
2
+
3
+ Validate the check digits in a passport or ID card **machine-readable zone (MRZ)**, as defined by ICAO Document 9303. Supports all three layouts:
4
+
5
+ | Layout | Used on | Shape |
6
+ | ------ | ------------------------ | ------------------ |
7
+ | TD1 | ID cards | 3 lines × 30 chars |
8
+ | TD2 | Older ID cards, visas | 2 lines × 36 chars |
9
+ | TD3 | Passports | 2 lines × 44 chars |
10
+
11
+ It checks the document number, date of birth and expiry date digits, the TD3 optional-data digit, and the composite digit. Pure Python, no dependencies, typed.
12
+
13
+ Use it after OCR to reject or retry a misread MRZ (`0`/`O`, `8`/`B`, `1`/`I` and similar) before it reaches your database.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pip install mrz-checkdigit
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```python
24
+ from mrz_checkdigit import check_digit, is_valid, validate
25
+
26
+ mrz = [
27
+ "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<",
28
+ "L898902C36UTO7408122F1204159ZE184226B<<<<<10",
29
+ ]
30
+
31
+ is_valid(mrz) # True
32
+ check_digit("L898902C3") # 6
33
+
34
+ for r in validate(mrz):
35
+ print(r.field, r.expected, r.computed, r.ok)
36
+ # document_number 6 6 True
37
+ # birth_date 2 2 True
38
+ # expiry_date 9 9 True
39
+ # optional_data 1 1 True
40
+ # composite 0 0 True
41
+ ```
42
+
43
+ The layout is detected from the number and length of the lines. `validate` raises `ValueError` for any other shape.
44
+
45
+ ### Command line
46
+
47
+ ```bash
48
+ mrz-checkdigit 'P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<' 'L898902C36UTO7408122F1204159ZE184226B<<<<<10'
49
+ ```
50
+
51
+ Lines can also be piped on stdin. Exit code is `0` when every digit matches, `1` when one fails, `2` for an unrecognised layout.
52
+
53
+ ## The algorithm
54
+
55
+ Each character becomes a number (digits keep their value, `A`–`Z` = 10–35, `<` = 0), is multiplied by the repeating weights 7, 3, 1, and the check digit is the sum modulo 10.
56
+
57
+ ## Background
58
+
59
+ The full walkthrough, with the field positions, the composite digit and why OCR pipelines depend on it: [How passport MRZ check digits work, with code to validate them](https://aliahmed.si/blog/passport-mrz-check-digits/).
60
+
61
+ Check digits catch accidental errors. They are not a security feature: anyone can compute valid digits. Proving a document is genuine takes authenticity checks or reading the signed NFC chip.
62
+
63
+ ## Limitations
64
+
65
+ - TD1 document numbers longer than 9 characters (the overflow into the optional field) are not handled yet.
66
+ - Only check digits are validated; field formats (dates, country codes) are not.
67
+
68
+ ## License
69
+
70
+ MIT
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "mrz-checkdigit"
7
+ dynamic = ["version"]
8
+ description = "Validate passport and ID card MRZ check digits (ICAO 9303: TD1, TD2, TD3)"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "Ali Ahmed" }]
14
+ keywords = ["mrz", "passport", "icao", "icao-9303", "check-digit", "ocr", "kyc", "id-card"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Scientific/Engineering :: Image Recognition",
20
+ "Topic :: Software Development :: Libraries",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://aliahmed.si/"
26
+ Documentation = "https://aliahmed.si/blog/passport-mrz-check-digits/"
27
+ Source = "https://github.com/QuantumBreakz/mrz-checkdigit"
28
+ Issues = "https://github.com/QuantumBreakz/mrz-checkdigit/issues"
29
+
30
+ [project.scripts]
31
+ mrz-checkdigit = "mrz_checkdigit:main"
32
+
33
+ [tool.hatch.version]
34
+ path = "src/mrz_checkdigit/__init__.py"
@@ -0,0 +1,113 @@
1
+ """Validate ICAO 9303 machine-readable zone (MRZ) check digits.
2
+
3
+ Supports TD1 (ID cards, 3x30), TD2 (2x36) and TD3 (passports, 2x44).
4
+ Check digits catch OCR and transcription errors; they do not prove a
5
+ document is genuine.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import sys
12
+ from typing import NamedTuple, Sequence
13
+
14
+ __all__ = ["CheckResult", "check_digit", "validate", "is_valid", "main"]
15
+ __version__ = "0.1.0"
16
+
17
+ _WEIGHTS = (7, 3, 1)
18
+
19
+
20
+ class CheckResult(NamedTuple):
21
+ field: str
22
+ data: str
23
+ expected: str # check character printed on the document
24
+ computed: int
25
+
26
+ @property
27
+ def ok(self) -> bool:
28
+ if self.expected == "<":
29
+ # ICAO allows a filler instead of a digit when the field is all fillers.
30
+ return set(self.data) <= {"<"}
31
+ return self.expected == str(self.computed)
32
+
33
+
34
+ def _value(ch: str) -> int:
35
+ if "0" <= ch <= "9":
36
+ return ord(ch) - ord("0")
37
+ if "A" <= ch <= "Z":
38
+ return ord(ch) - ord("A") + 10
39
+ if ch == "<":
40
+ return 0
41
+ raise ValueError(f"invalid MRZ character: {ch!r}")
42
+
43
+
44
+ def check_digit(field: str) -> int:
45
+ """Return the ICAO 9303 check digit (weights 7, 3, 1; A-Z = 10-35; '<' = 0)."""
46
+ return sum(_value(ch) * _WEIGHTS[i % 3] for i, ch in enumerate(field)) % 10
47
+
48
+
49
+ def _check(name: str, data: str, expected: str) -> CheckResult:
50
+ return CheckResult(name, data, expected, check_digit(data))
51
+
52
+
53
+ def validate(lines: Sequence[str]) -> list[CheckResult]:
54
+ """Check every check digit in an MRZ. Layout is detected from the line shape."""
55
+ lines = [line.strip().upper() for line in lines]
56
+ shape = (len(lines), {len(line) for line in lines})
57
+ if shape == (3, {30}): # TD1
58
+ l1, l2, _ = lines
59
+ return [
60
+ _check("document_number", l1[5:14], l1[14]),
61
+ _check("birth_date", l2[0:6], l2[6]),
62
+ _check("expiry_date", l2[8:14], l2[14]),
63
+ _check("composite", l1[5:30] + l2[0:7] + l2[8:15] + l2[18:29], l2[29]),
64
+ ]
65
+ if shape == (2, {36}): # TD2
66
+ l2 = lines[1]
67
+ return [
68
+ _check("document_number", l2[0:9], l2[9]),
69
+ _check("birth_date", l2[13:19], l2[19]),
70
+ _check("expiry_date", l2[21:27], l2[27]),
71
+ _check("composite", l2[0:10] + l2[13:20] + l2[21:35], l2[35]),
72
+ ]
73
+ if shape == (2, {44}): # TD3
74
+ l2 = lines[1]
75
+ return [
76
+ _check("document_number", l2[0:9], l2[9]),
77
+ _check("birth_date", l2[13:19], l2[19]),
78
+ _check("expiry_date", l2[21:27], l2[27]),
79
+ _check("optional_data", l2[28:42], l2[42]),
80
+ _check("composite", l2[0:10] + l2[13:20] + l2[21:43], l2[43]),
81
+ ]
82
+ raise ValueError(
83
+ "unrecognised MRZ layout: expected 3 lines of 30 (TD1), "
84
+ "2 of 36 (TD2) or 2 of 44 (TD3) characters"
85
+ )
86
+
87
+
88
+ def is_valid(lines: Sequence[str]) -> bool:
89
+ """True if every check digit in the MRZ matches."""
90
+ return all(r.ok for r in validate(lines))
91
+
92
+
93
+ def main(argv: Sequence[str] | None = None) -> int:
94
+ parser = argparse.ArgumentParser(
95
+ prog="mrz-checkdigit",
96
+ description="Validate ICAO 9303 MRZ check digits (TD1, TD2, TD3).",
97
+ )
98
+ parser.add_argument("lines", nargs="*", help="MRZ lines; read from stdin if omitted")
99
+ args = parser.parse_args(argv)
100
+ lines = args.lines or [line for line in sys.stdin.read().splitlines() if line.strip()]
101
+ try:
102
+ results = validate(lines)
103
+ except ValueError as exc:
104
+ print(f"error: {exc}", file=sys.stderr)
105
+ return 2
106
+ for r in results:
107
+ status = "ok " if r.ok else "FAIL"
108
+ print(f"{status} {r.field:<16} printed={r.expected} computed={r.computed}")
109
+ return 0 if all(r.ok for r in results) else 1
110
+
111
+
112
+ if __name__ == "__main__":
113
+ sys.exit(main())
File without changes
@@ -0,0 +1,57 @@
1
+ import pytest
2
+
3
+ from mrz_checkdigit import check_digit, is_valid, main, validate
4
+
5
+ # ICAO 9303 specimens (Parts 4, 5 and 6), fictional state "Utopia".
6
+ TD3 = [
7
+ "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<",
8
+ "L898902C36UTO7408122F1204159ZE184226B<<<<<10",
9
+ ]
10
+ TD1 = [
11
+ "I<UTOD231458907<<<<<<<<<<<<<<<",
12
+ "7408122F1204159UTO<<<<<<<<<<<6",
13
+ "ERIKSSON<<ANNA<MARIA<<<<<<<<<<",
14
+ ]
15
+ TD2 = [
16
+ "I<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<",
17
+ "D231458907UTO7408122F1204159<<<<<<<6",
18
+ ]
19
+
20
+
21
+ def test_check_digit_examples():
22
+ assert check_digit("L898902C3") == 6
23
+ assert check_digit("740812") == 2
24
+ assert check_digit("120415") == 9
25
+ assert check_digit("<<<<") == 0
26
+
27
+
28
+ @pytest.mark.parametrize("mrz", [TD1, TD2, TD3], ids=["TD1", "TD2", "TD3"])
29
+ def test_specimens_validate(mrz):
30
+ results = validate(mrz)
31
+ assert all(r.ok for r in results), results
32
+ assert is_valid(mrz)
33
+
34
+
35
+ @pytest.mark.parametrize("mrz", [TD1, TD2, TD3], ids=["TD1", "TD2", "TD3"])
36
+ def test_ocr_misread_is_caught(mrz):
37
+ # Classic OCR confusion: '0' read as 'O' in the date of birth.
38
+ bad = [line.replace("740812", "74O812") for line in mrz]
39
+ assert not is_valid(bad)
40
+
41
+
42
+ def test_filler_optional_check_digit():
43
+ line2 = "L898902C36UTO7408122F1204159<<<<<<<<<<<<<<<0"
44
+ line2 = line2[:42] + "<" + line2[43:]
45
+ by_field = {r.field: r for r in validate([TD3[0], line2])}
46
+ assert by_field["optional_data"].ok
47
+
48
+
49
+ def test_bad_layout():
50
+ with pytest.raises(ValueError):
51
+ validate(["P<UTO", "L898"])
52
+
53
+
54
+ def test_cli(capsys):
55
+ assert main(TD3) == 0
56
+ assert main([TD3[0], TD3[1].replace("L898", "L89B")]) == 1
57
+ assert "FAIL document_number" in capsys.readouterr().out