### Install fastmrz from source Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/README.md Clone the repository and install from source. Requires git and pip. ```bash git clone https://github.com/sivakumar-mahalingam/fastmrz.git cd fastmrz pip install . ``` -------------------------------- ### FastMRZ example output Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/getting-started.md Example output from the basic usage snippet. Shows the parsed JSON result with fields like mrz_type, document_code, and status, followed by the raw MRZ text. ```console { "mrz_type": "TD3", "document_code": "P", "issuer_code": "GBR", "document_number": "707797979", "surname": "PUDARSAN", "given_name": "HENERT", "nationality_code": "GBR", "birth_date": "1995-05-20", "sex": "M", "expiry_date": "2017-04-22", "optional_data": "", "mrz_text": "P/fastmrz.git cd fastmrz pip install -e . python -m unittest tests.test_fastmrz ``` -------------------------------- ### Install FastMRZ with uv Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/getting-started.md Installs the FastMRZ package using the uv package manager. ```bash uv pip install fastmrz ``` -------------------------------- ### Install MkDocs and serve documentation site Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/contributing.md Commands to install MkDocs with Material theme and mkdocstrings, serve locally, and build the static site with strict checks as CI would. ```bash # Install MkDocs and plugins pip install mkdocs mkdocs-material mkdocstrings[python] # Serve locally mkdocs serve # Build static site (as CI would) mkdocs build --strict ``` -------------------------------- ### Basic usage of FastMRZ with various input types Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/README.md Initialize FastMRZ once and reuse it across threads. get_details accepts image paths, numpy arrays, base64 strings, bytes, PDFs, or raw MRZ text. Use ignore_parse to get raw MRZ text, get_details_batch for parallel processing, validate_mrz for validation, and get_mrz_image for a rectified crop. ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() # loads the model once; safe to share across threads # Parsed fields from any supported input details = fast_mrz.get_details("data/td3.jpg") # image path (str or pathlib.Path) details = fast_mrz.get_details(image_array, input_type="numpy") # BGR or greyscale ndarray details = fast_mrz.get_details(b64_string, input_type="base64") # data: URIs allowed details = fast_mrz.get_details(image_bytes, input_type="bytes") # encoded JPEG, PNG, ... details = fast_mrz.get_details("scan.pdf", input_type="pdf") # path or bytes details = fast_mrz.get_details(mrz_string, input_type="text") # parse only, no OCR # Raw MRZ text instead of parsed fields text = fast_mrz.get_details("data/td3.jpg", ignore_parse=True) # Many documents in parallel, results in input order results = fast_mrz.get_details_batch(["a.jpg", "b.jpg", "c.jpg"]) # Validate MRZ text fast_mrz.validate_mrz(text) # {"is_valid": True, "status_message": "The given mrz is valid"} # Rectified MRZ crop, e.g. for display or auditing strip = fast_mrz.get_mrz_image("data/td3.jpg") ``` -------------------------------- ### Migrating FastMRZ 2.x code to 3.x Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/getting-started.md Shows the 2.x constructor with tesseract_path and the 3.x replacement. In v3, tesseract_path and tessdata_path are ignored and raise a FutureWarning; remove them. ```python # 2.x fast_mrz = FastMRZ(tesseract_path=r"C:\Program Files\Tesseract-OCR\tesseract.exe") # 3.x fast_mrz = FastMRZ() ``` -------------------------------- ### Install FastMRZ with pip Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/index.md Install the FastMRZ package using pip. This is the first step before using the library. ```bash pip install fastmrz ``` -------------------------------- ### FastMRZ custom recogniser model Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/getting-started.md Passes a custom ONNX model path to FastMRZ for MRZ recognition. ```python fast_mrz = FastMRZ(model_path="path/to/mrz_rec.onnx") ``` -------------------------------- ### Read MRZ details from an image using FastMRZ Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/README.md Create a FastMRZ instance and call get_details with an image path to extract parsed MRZ fields. ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() details = fast_mrz.get_details("data/td3.jpg") ``` -------------------------------- ### get_details_batch Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/README.md Processes a batch of inputs and returns a list of get_details results in input order. Unreadable inputs become FAILURE entries instead of raising exceptions. ```APIDOC ## get_details_batch(inputs, input_type="imagepath", ignore_parse=False, include_checkdigit=True, workers=None) ### Description Processes a batch of inputs and returns a list of get_details results in input order. Unreadable inputs become FAILURE entries instead of raising exceptions. ### Parameters - **inputs** - Required - List of input data items - **input_type** (str) - Optional - Type of input: "imagepath", "numpy", "base64", "bytes", "pdf", or "text" - **ignore_parse** (bool) - Optional - If True, returns raw MRZ text for each input - **include_checkdigit** (bool) - Optional - If False, omits check-digit keys from the output - **workers** (int) - Optional - Number of worker processes; defaults to number of CPUs capped at 8 ### Returns - **list** - List of get_details results, in input order; unreadable inputs become FAILURE entries ``` -------------------------------- ### get_details_batch usage example Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/api-reference.md Example call to get_details_batch with a list of image paths. Results are returned in input order; an unreadable input yields a FAILURE status instead of stopping the batch. ```python results = fast_mrz.get_details_batch(["a.jpg", "b.jpg", "missing.jpg"]) # [{... "status": "SUCCESS"}, {...}, {"status": "FAILURE", "status_message": "Input is not a valid image file."}] ``` -------------------------------- ### Bug Report Example Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/contributing.md Template for reporting a bug, including steps to reproduce, expected vs actual behavior, and environment details. ```text Title: MRZ detection fails on low-light passport images Steps to Reproduce: 1. Load a passport image taken in low-light conditions 2. Call fast_mrz.get_details("passport_dark.jpg") 3. Observe the output Expected: Parsed MRZ data with status SUCCESS Actual: {'status': 'FAILURE', 'status_message': 'No MRZ detected'} Environment: - OS: Ubuntu 22.04 - Python: 3.10 - FastMRZ: 3.1.1 - OpenCV: 4.10.0 ``` -------------------------------- ### get_details_batch Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/README.md Processes multiple documents in parallel and returns results in input order. Each entry is a dictionary with parsed fields or a FAILURE status for unreadable inputs. ```APIDOC ## get_details_batch ### Description Processes multiple documents in parallel and returns results in input order. Each entry is a dictionary with parsed fields or a FAILURE status for unreadable inputs. ### Method Function call ### Parameters - **inputs** (list) - Required - List of inputs, each can be a path, numpy array, base64 string, bytes, PDF, or MRZ text. ### Response Returns a list of dictionaries, one per input, in the same order. Each dictionary contains parsed fields or a "FAILURE" status with a status message. ### Request Example ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() results = fast_mrz.get_details_batch(["a.jpg", "b.jpg", "c.jpg"]) ``` ``` -------------------------------- ### FastMRZ basic usage with JSON output Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/getting-started.md Creates a FastMRZ instance and extracts MRZ details from an image. The include_checkdigit=False option omits check digits from the result. The ignore_parse=True option returns the raw MRZ text instead of parsed fields. One FastMRZ instance loads the model once and can be shared across threads. ```python from fastmrz import FastMRZ import json fast_mrz = FastMRZ() result = fast_mrz.get_details("data/passport_uk.jpg", include_checkdigit=False) print(json.dumps(result, indent=4)) text = fast_mrz.get_details("data/passport_uk.jpg", ignore_parse=True) print(text) ``` -------------------------------- ### FastMRZ Constructor Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/README.md Initializes the FastMRZ object. The constructor accepts an optional custom ONNX model path; the tesseract_path and tessdata_path parameters are deprecated and ignored, raising a FutureWarning if provided. ```APIDOC ## FastMRZ(tesseract_path="", tessdata_path="", model_path=None) ### Description Initializes the FastMRZ object. The constructor accepts an optional custom ONNX model path; the tesseract_path and tessdata_path parameters are deprecated and ignored, raising a FutureWarning if provided. ### Parameters - **model_path** (str | PathLike | None) - Optional - Custom recogniser ONNX model; defaults to the bundled one - **tesseract_path** (str) - Optional - Deprecated and ignored; passing a value raises FutureWarning - **tessdata_path** (str) - Optional - Deprecated and ignored; passing a value raises FutureWarning ``` -------------------------------- ### Set up development environment with pip Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/contributing.md Clone the repository, create a virtual environment, and install in editable mode. Requires Python 3.8+ and Git. Activate the environment with 'source venv/bin/activate' on Unix or 'venv\Scripts\activate' on Windows. ```bash # Clone your fork git clone https://github.com/YOUR_USERNAME/fastmrz.git cd fastmrz # Create a virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install in editable mode pip install -e . ``` -------------------------------- ### FastMRZ instantiation example Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/api-reference.md Create a FastMRZ instance with default model or a custom ONNX model. Missing or invalid model_path raises OSError or cv2.error immediately. ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() # With a custom recogniser model fast_mrz = FastMRZ(model_path="models/mrz_rec.onnx") ``` -------------------------------- ### get_mrz_image Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/README.md Returns a rectified MRZ crop from an image, useful for display or auditing. ```APIDOC ## get_mrz_image ### Description Returns a rectified MRZ crop from an image, useful for display or auditing. ### Method Function call ### Parameters - **input** (str, pathlib.Path, numpy.ndarray, bytes) - Required - The input image (path, numpy array, base64, bytes, or PDF). ### Response Returns the rectified MRZ crop image. ### Request Example ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() strip = fast_mrz.get_mrz_image("data/td3.jpg") ``` ``` -------------------------------- ### Flask web upload example for Base64 input Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Example of a Flask endpoint that receives a Base64 image in a JSON request and processes it with FastMRZ. The image is extracted from the request JSON and passed to get_details with input_type='base64'. ```python from flask import Flask, request, jsonify from fastmrz import FastMRZ app = Flask(__name__) fast_mrz = FastMRZ() @app.route("/extract-mrz", methods=["POST"]) def extract_mrz(): # Get Base64 from request data = request.json b64_image = data["image"] # Process result = fast_mrz.get_details(b64_image, input_type="base64") return jsonify(result) ``` -------------------------------- ### validate_mrz usage example Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/api-reference.md Example call to validate_mrz with a sample MRZ string and printing the is_valid flag. ```python result = fast_mrz.validate_mrz( "P Union[MRZDetails, str] ``` -------------------------------- ### NumPy Array Input with OpenCV Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Pass an image as a NumPy array, e.g., loaded with OpenCV. Colour images must be in BGR order; greyscale is accepted. Extra channels are ignored and non-uint8 arrays are rescaled. ```python import cv2 import numpy as np from fastmrz import FastMRZ fast_mrz = FastMRZ() # Load image with OpenCV image = cv2.imread("passport.jpg") # Pass directly to FastMRZ result = fast_mrz.get_details(image, input_type="numpy") ``` -------------------------------- ### Process data URL with FastMRZ Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Shows that a data URL prefix (e.g., 'data:image/jpeg;base64,...') is stripped automatically before processing. The data URL is passed directly to get_details with input_type='base64'. ```python import base64 from fastmrz import FastMRZ fast_mrz = FastMRZ() # Data URL from browser data_url = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ..." result = fast_mrz.get_details(data_url, input_type="base64") ``` -------------------------------- ### get_details with Base64 String Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Process a Base64-encoded image string to extract MRZ details. Useful for web applications where images are transmitted as Base64. The method automatically strips data URL prefixes. ```APIDOC ## get_details(input, input_type="base64") ### Description Process a Base64-encoded image string to extract MRZ details. Useful for web applications where images are transmitted as Base64. The method automatically strips data URL prefixes. ### Method Python method call ### Parameters - **input** (str) - Required - Base64-encoded image string or data URL - **input_type** (str) - Optional - Set to "base64" ### Response Returns the MRZ extraction result. ### Request Example ```python import base64 from fastmrz import FastMRZ fast_mrz = FastMRZ() # Encode image to Base64 with open("passport.jpg", "rb") as f: b64_string = base64.b64encode(f.read()).decode("utf-8") # Process Base64 string result = fast_mrz.get_details(b64_string, input_type="base64") ``` ### Request Example (Flask) ```python from flask import Flask, request, jsonify from fastmrz import FastMRZ app = Flask(__name__) fast_mrz = FastMRZ() @app.route("/extract-mrz", methods=["POST"]) def extract_mrz(): # Get Base64 from request data = request.json b64_image = data["image"] # Process result = fast_mrz.get_details(b64_image, input_type="base64") return jsonify(result) ``` ### Request Example (Data URL) ```python import base64 from fastmrz import FastMRZ fast_mrz = FastMRZ() # Data URL from browser data_url = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ..." result = fast_mrz.get_details(data_url, input_type="base64") ``` ``` -------------------------------- ### get_details with raw MRZ text input Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Pass pre-extracted MRZ text directly to the get_details method with input_type='text'. This skips image processing and parses the text exactly as given (upper-cased, whitespace removed) without auto-correction. ```APIDOC ## get_details(input, input_type="text") ### Description Pass pre-extracted MRZ text directly for parsing and validation. This skips the image processing pipeline entirely. The text is parsed exactly as given (upper-cased, whitespace removed) and never auto-corrected. ### Method `get_details` ### Parameters - **input** (str) - Required - MRZ text - **input_type** (str) - Required - Set to `"text"` ### Response Returns the parsed MRZ details. ### Request Example ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() mrz_text = ( "P List[Union[MRZDetails, str]] ``` -------------------------------- ### NumPy Array Input Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Pass an image directly as a NumPy array. Useful when the image is already loaded in memory or obtained from another library. ```APIDOC ## NumPy Array Input ### Description Pass an image directly as a NumPy array. Useful when the image is already loaded in memory or obtained from another library. ### Method `get_details` ### Parameters - **image** (np.ndarray) - Required - Image as a NumPy array (BGR colour or greyscale) - **input_type** (str) - Required - Set to `"numpy"` ### Response Returns the MRZ details extracted from the image. ### Request Example ```python import cv2 import numpy as np from fastmrz import FastMRZ fast_mrz = FastMRZ() # Load image with OpenCV image = cv2.imread("passport.jpg") # Pass directly to FastMRZ result = fast_mrz.get_details(image, input_type="numpy") ``` ```python from PIL import Image import numpy as np from fastmrz import FastMRZ fast_mrz = FastMRZ() # Load with PIL as greyscale (avoids the RGB vs BGR question) pil_image = Image.open("passport.jpg").convert("L") image_array = np.array(pil_image) result = fast_mrz.get_details(image_array, input_type="numpy") ``` ```python import cv2 from fastmrz import FastMRZ fast_mrz = FastMRZ() cap = cv2.VideoCapture(0) ret, frame = cap.read() if ret: result = fast_mrz.get_details(frame, input_type="numpy") print(result) cap.release() ``` ``` -------------------------------- ### get_details with Image Bytes Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Process the encoded bytes of an image file to extract MRZ details. Useful for images from HTTP uploads or object storage. The bytes must decode to an image format OpenCV can read. ```APIDOC ## get_details(input, input_type="bytes") ### Description Process the encoded bytes of an image file to extract MRZ details. Useful for images from HTTP uploads or object storage. The bytes must decode to an image format OpenCV can read. ### Method Python method call ### Parameters - **input** (bytes) - Required - Encoded image bytes - **input_type** (str) - Optional - Set to "bytes" ### Response Returns the MRZ extraction result. ### Request Example ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() with open("passport.jpg", "rb") as f: result = fast_mrz.get_details(f.read(), input_type="bytes") ``` ``` -------------------------------- ### Push Feature Branch Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/contributing.md Command to push the feature branch to the remote repository. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Detect MRZ document type based on line count and length Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/supported-documents.md Determines the MRZ type (TD1, TD2, TD3, MRVA, MRVB) from the number of lines and characters per line. Two lines indicate TD2/TD3/MRVA/MRVB, three lines indicate TD1; a trailing '<' on the second line indicates a visa type. ```python if len(mrz_lines) == 2: if mrz_lines[1][-1] == "<": mrz_type = "MRVB" if len(mrz_lines[0]) == 36 else "MRVA" else: mrz_type = "TD2" if len(mrz_lines[0]) == 36 else "TD3" else: mrz_type = "TD1" ``` -------------------------------- ### validate_mrz return values Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/api-reference.md Shows the return dictionary for a valid MRZ and for an invalid MRZ with a checksum mismatch. ```python # Valid MRZ { "is_valid": True, "status_message": "The given mrz is valid" } # Invalid MRZ { "is_valid": False, "status_message": "Document number checksum is not matching" } ``` -------------------------------- ### Process Base64 image string with FastMRZ Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Pass a Base64-encoded image string to FastMRZ. Useful for web applications where images are transmitted as Base64. The string must be valid Base64 and decode to a valid image format. ```python import base64 from fastmrz import FastMRZ fast_mrz = FastMRZ() # Encode image to Base64 with open("passport.jpg", "rb") as f: b64_string = base64.b64encode(f.read()).decode("utf-8") # Process Base64 string result = fast_mrz.get_details(b64_string, input_type="base64") ``` -------------------------------- ### get_mrz_image Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/api-reference.md Return the MRZ as the recogniser saw it. Returns a greyscale uint8 array of the rectified MRZ lines stacked top to bottom, or None when no MRZ is found. ```APIDOC ## get_mrz_image ### Description Return the MRZ as the recogniser saw it. Returns a greyscale uint8 array of the rectified MRZ lines stacked top to bottom, or None when no MRZ is found. ### Method Function call ### Endpoint `get_mrz_image(input_data, input_type='imagepath')` ### Parameters - **input_data** (InputData) - Required - The input document. - **input_type** (InputType) - Optional - As for `get_details`; `"text"` is not supported. ### Response #### Success Response A greyscale `uint8` array: the rectified MRZ lines stacked top to bottom, each 32 x 640 pixels (so 64 x 640 for two-line formats, 96 x 640 for TD1). `None` when no MRZ is found. ### Errors - `ValueError`: the input cannot be read. ### Request Example ```python import cv2 strip = fast_mrz.get_mrz_image("passport.jpg") if strip is not None: cv2.imwrite("mrz.png", strip) # 64 x 640 for a passport ``` ``` -------------------------------- ### get_mrz_image function signature Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/api-reference.md Signature for returning the MRZ as the recogniser saw it. input_type "text" is not supported. Returns a greyscale uint8 array or None when no MRZ is found; raises ValueError if the input cannot be read. ```python get_mrz_image( input_data: InputData, input_type: InputType = "imagepath", ) -> Optional[numpy.ndarray] ``` -------------------------------- ### Process image bytes with FastMRZ Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Pass the encoded bytes of an image file, e.g. from an HTTP upload or object storage. The bytes must decode to an image OpenCV can read (JPEG, PNG, BMP, TIFF, WebP, ...). ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() with open("passport.jpg", "rb") as f: result = fast_mrz.get_details(f.read(), input_type="bytes") ``` -------------------------------- ### Automatic Validation with get_details() Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/checksum-validation.md Calls get_details() to automatically validate all check digits. On failure, the result status is 'FAILURE' and status_message contains the error. ```python result = fast_mrz.get_details("passport.jpg") if result["status"] == "FAILURE": print(f"Validation failed: {result['status_message']}") ``` -------------------------------- ### Raw MRZ Text Input: Parse and Validate Source: https://github.com/sivakumar-mahalingam/fastmrz/blob/main/docs/input-formats.md Pass pre-extracted MRZ text directly for parsing and validation, skipping the image processing pipeline. The text is parsed exactly as given (upper-cased, whitespace removed) and never auto-corrected. Useful for validating MRZ text from another OCR engine, parsing from a database, testing, or manual input. ```python from fastmrz import FastMRZ fast_mrz = FastMRZ() mrz_text = ( "P Dict[str, Union[bool, str]] ```