npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mrz-genius

v2.0.1

Published

Node.js library for MRZ detection, OCR, and parsing from identity documents (TD1, TD2, TD3, MRVA, MRVB)

Readme

mrz-genius

npm version License: MIT Node.js Version Build Status

Bibliothèque Node.js complète pour la détection, l' OCR et le parsing des zones MRZ (Machine Readable Zone) sur les documents d'identité.

📍 Workflow d'extraction

graph LR
    A[Image Brute] --> B[Détection Zone MRZ]
    B --> C[Optimisation Image]
    C --> D[OCR Tesseract/LLM]
    D --> E[Parsing & Correction]
    E --> F[Données ID Validées]
    style F fill:#10b981,stroke:#059669,color:#fff

Inspirée du module Swift MRZParser.

📋 Formats supportés

| Format | Type de document | Lignes | Caractères/ligne | |--------|-----------------|--------|------------------| | TD1 | Cartes d'identité (CNI) | 3 | 30 | | TD2 | Documents de voyage (format moyen) | 2 | 36 | | TD3 | Passeports | 2 | 44 | | MRVA | Visas type A | 2 | 44 | | MRVB | Visas type B | 2 | 36 |

🚀 Installation

npm install mrz-genius

Ou depuis les sources :

cd mrz-genius
npm install

📖 Utilisation

1. Pipeline complet : Image → MRZ parsé

const { processImage } = require('mrz-genius');

// Depuis un fichier image
const result = await processImage('./passport.jpg');

if (result.success) {
  console.log('Nom:', result.parsed.surname);
  console.log('Prénoms:', result.parsed.givenNames);
  console.log('N° Document:', result.parsed.documentNumber);
  console.log('Nationalité:', result.parsed.nationality);
  console.log('Date naissance:', result.parsed.birthDateFormatted);
  console.log('Date expiration:', result.parsed.expiryDateFormatted);
  console.log('Sexe:', result.parsed.sex);
}

2. Parser direct (texte MRZ)

const { parseMRZ } = require('mrz-genius');

// TD3 - Passeport
const result = parseMRZ([
  'P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<',
  'L898902C36UTO7408122F1204159ZE184226B<<<<<10'
]);

console.log(result);
// {
//   success: true,
//   ocr: { confidence: 98, method: 'full_image_threshold_140_3x' },
//   parsed: {
...
//     surname: 'TOURE',
//     documentNumber: 'CI0086201',
//     ...
//   }
// }

### 2. Option avec LLM (ChatGPT, Claude, Gemini)

Pour remplacer l'OCR classique par les capacités de vision surpuissantes d'un modèle d'IA :

```javascript
const result = await processImage('./document.jpg', {
  llm: {
    provider: 'chatgpt', // ou 'anthropic', 'gemini', 'litellm'
    apiKey: process.env.API_KEY,
    model: 'gpt-4o' // (Optionnel) modèle spécifique
  }
});

3. Parser direct (texte MRZ)

//   issuingCountry: 'UTO',
//   surname: 'ERIKSSON',
//   givenNames: 'ANNA MARIA',
//   documentNumber: 'L898902C3',
//   nationality: 'UTO',
//   birthDate: Date,
//   birthDateFormatted: '1974-08-12',
//   sex: 'FEMALE',
//   expiryDate: Date,
//   expiryDateFormatted: '2012-04-15',
//   optionalData1: 'ZE184226B',
//   ...
// }

3. Parsing avec texte multi-ligne

const { parseMRZ } = require('mrz-genius');

// TD1 - Carte d'identité
const mrz = `I<UTOD231458907<<<<<<<<<<<<<<<
7408122F1204159UTO<<<<<<<<<<<6
ERIKSSON<<ANNA<MARIA<<<<<<<<<<`;

const result = parseMRZ(mrz);

4. Détection de la zone MRZ sur image

const { detectMRZRegion } = require('mrz-genius');

const region = await detectMRZRegion('./document.jpg');
console.log('Région MRZ:', region.x, region.y, region.width, region.height);
console.log('Confiance:', region.confidence);
// region.imageBuffer contient l'image croppée de la zone MRZ

5. OCR seul

const { performOCR } = require('mrz-genius');

const ocrResult = await performOCR('./passport.jpg');
console.log('Lignes MRZ:', ocrResult.lines);
console.log('Confiance OCR:', ocrResult.confidence);

6. Correction OCR

const { parseMRZ } = require('mrz-genius');

// Avec correction des erreurs OCR courantes (O→0, I→1, etc.)
const result = parseMRZ(mrzText, { ocrCorrection: true });

7. Vérification de présence MRZ

const { hasMRZ } = require('mrz-genius');

const containsMRZ = await hasMRZ('./document.jpg');
console.log('Document contient un MRZ:', containsMRZ);

🔧 API Complète

Haut niveau

| Fonction | Description | |----------|-------------| | processImage(image, options?) | Pipeline complet : détection + OCR + parsing | | parseMRZ(text, options?) | Parse un texte MRZ directement |

Détection

| Fonction | Description | |----------|-------------| | detectMRZRegion(input, options?) | Détecte la zone MRZ dans une image | | optimizeForOCR(buffer, options?) | Optimise une image pour l'OCR | | preprocessForOCR(input, options?) | Détection + optimisation combinées |

OCR

| Fonction | Description | |----------|-------------| | performOCR(input, options?) | OCR Tesseract optimisé pour MRZ | | hasMRZ(input) | Vérifie si une image contient un MRZ |

Validation

| Fonction | Description | |----------|-------------| | calculateCheckDigit(value) | Calcule le chiffre de contrôle ICAO | | isCheckDigitValid(value, digit) | Valide un chiffre de contrôle | | isCompositeValid(fields, digit) | Valide le chiffre de contrôle composite |

Correction OCR

| Fonction | Description | |----------|-------------|

Correction OCR (Heuristiques d'auto-réparation)

| Fonction | Description | |----------|-------------| | correctOCR(str, contentType) | Corrige les erreurs OCR courantes simples | | repairFieldWithCheckDigit(val, cd)| Répare par brute-force les confusions en vérifiant le Check Digit | | repairIvorianDocumentNumber(doc) | Corrige de force un numéro CNI pour correspondre aux normes Ivoiriennes |

📦 Structure du résultat

interface MRZResult {
  valid: boolean;             // Tous les chiffres de contrôle sont valides
  format: string;             // TD1, TD2, TD3, MRVA, MRVB
  documentType: string;       // PASSPORT, VISA, ID_CARD
  issuingCountry: string;     // Code pays ISO 3166-1 (3 lettres)
  surname: string;            // Nom de famille
  givenNames: string | null;  // Prénoms
  documentNumber: string;     // Numéro du document
  nationality: string;        // Code nationalité
  birthDate: Date;            // Date de naissance
  birthDateFormatted: string; // Format YYYY-MM-DD
  sex: string;                // MALE, FEMALE, UNSPECIFIED
  expiryDate: Date | null;    // Date d'expiration
  expiryDateFormatted: string;
  optionalData1: string | null;
  optionalData2: string | null;  // TD1 uniquement
  mrzKey: string;             // Clé BAC pour e-Passeports
  rawMRZ: string;             // MRZ brut
  details: {                  // Détails de validation
    fields: { ... },
    finalCheckDigitValid: boolean
  };
}

🧪 Tests

npm test

📐 Distribution des champs

TD1 (Carte d'identité) — 3 lignes × 30 caractères
┌─────────────────────────────────────┐
│ Ligne 1: Type|Pays|N°Document|Opt1  │
│ Ligne 2: DDN|S|Exp|Nat|Opt2|Check   │
│ Ligne 3: NOM<<PRÉNOMS               │
└─────────────────────────────────────┘

TD3 (Passeport) — 2 lignes × 44 caractères
┌────────────────────────────────────────────────┐
│ Ligne 1: Type|Pays|NOM<<PRÉNOMS                │
│ Ligne 2: N°Doc|Nat|DDN|S|Exp|Opt1|Check        │
└────────────────────────────────────────────────┘

📄 Licence

MIT