Morocco CNIE OCR Python SDK

Instantly extract data from Moroccan IDs using our native Python library.

AI extracting data from a Morocco ID card
StructOCR engine analyzing a Moroccan document in real-time.

Parsing CNIE Challenges

Extracting data from Moroccan CNIEs presents unique challenges. Firstly, the combination of Arabic script alongside Latin characters requires a sophisticated OCR engine. Secondly, the variations in CNIE layouts over the years and potential low print quality further complicate accurate data extraction.

Why StructOCR for Morocco

Our OCR model is specifically trained on a vast dataset of Moroccan CNIEs, covering various layouts and image qualities. This advanced id card parsing capability ensures high accuracy. The Python SDK provides a simple and efficient way to integrate this powerful engine into your applications, abstracting away the complexities of image preprocessing and API interaction for seamless information parsing.

Common Use Cases in Morocco

  • Digital Onboarding: Verify users for Fintech apps in Morocco.
  • Telecom Registration: Automate SIM card registration with CNIE.
  • Hotel Check-in: Speed up guest registration workflows.

Live Demo: ID card scanner

No registration required. Upload a file to test the extraction.

1
Upload
2
Results

Drop files here or click to browse

JPG · PNG · WebP  ·  up to 500 files · max 4.5 MB each

No files selected
Need more testing? Create a free account to get 200 free credits (equals 100 National ID scans).

Python SDK Integration

Install the SDK via pip: `pip install structocr`. Then use the following code.

Prerequisite: Python 3.6+ and `structocr` library installed.

from structocr import StructOCR

# 🔑 Need a key for Morocco? Get 200 free credits instantly:
# 👉 https://structocr.com/register
# Initialize with your API Key
client = StructOCR("YOUR_API_KEY_HERE")

def scan_morocco_id():
    # Note: Supports JPG, PNG, WebP (Max 4.5MB)
    # Target: CNIE
    image_path = "morocco_national_id.jpg"

    try:
        print(f"Scanning {image_path}...")
        
        # The SDK handles file upload and API communication
        # It automatically detects that this is a Moroccan document
        result = client.scan_national_id(image_path)

        # Check success flag (SDK returns a dict matching the JSON response)
        if result.get('success'):
            data = result['data']
            print("✅ Morocco Extraction Successful!")
            
            # Basic Identity
            print(f"Region:      {data.get('country_code')} (Series: {data.get('card_series')})")
            print(f"Name:        {data.get('given_names')} {data.get('surname')}")
            print(f"ID Number:   {data.get('document_number')}")
            
            # Critical Field: Personal Identity Number (CNP/CPF/NIN)
            print(f"Personal #:  {data.get('personal_number')}")
            
            # Demographics
            print(f"DOB:         {data.get('date_of_birth')} ({data.get('sex')})")
            print(f"Address:     {data.get('address')}")
            
            # MRZ Extraction
            additional = data.get('additional_fields', {})
            if additional.get('mrz_line_1'):
                print("\n🔍 MRZ Data Found:")
                print(additional.get('mrz_line_1'))
                print(additional.get('mrz_line_2'))
                print(additional.get('mrz_line_3') or "")
        else:
            print(f"❌ Extraction Failed: {result.get('error')}")

    except Exception as e:
        # Handle SDK or Network errors
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    scan_morocco_id()

Technical Specs

  • Latency: < 4s (Average)
  • Uptime: 99.9% SLA
  • Security: AES-256 Encryption & SOC2 Compliant
  • Input: JPG, PNG, WebP (Max 4.5MB)
  • Output: JSON (Structured Data)

Key Features

  • Native Script Support: Reads English and local characters.
  • MRZ Extraction: Automatically parses Machine Readable Zone (MRZ) lines for enhanced data validation and identity verification.
  • Blur Detection: Automatically rejects blurry images.
  • Fraud Check: Validates CNIE number format.
  • Smart Crop: Removes background noise automatically.

JSON Response Example

The SDK returns a Python dictionary matching this JSON structure.

{
  "success": true,
  "data": {
    "type": "national_id",
    "country_code": "MAR",
    "nationality": "MAROC",
    "document_number": "AB123456",
    "card_series": "",
    "personal_number": "AB123456",
    "surname": "ALAMI",
    "given_names": "YASSINE",
    "sex": "M",
    "date_of_birth": "1990-05-15",
    "place_of_birth": "CASABLANCA",
    "address": "12 Rue de la Marche Verte, Casablanca",
    "date_of_issue": "2020-01-01",
    "date_of_expiry": "2030-01-01",
    "issuing_authority": "DGSN",
    "additional_fields": {
      "phone_number": null,
      "tramite_number": null,
      "ejemplar": null,
      "mrz_line_1": "IDMARAB123456<<<<<<<<<<<<<<<<<",
      "mrz_line_2": "9005155M3001018MAR<<<<<<<<<<<6",
      "mrz_line_3": "ALAMI<<YASSINE<<<<<<<<<<<<<<<<"
    }
  }
}

Frequently Asked Questions

Does the Python SDK handle image uploads?

Yes, the SDK automatically handles base64 encoding and file uploads.

Is data stored?

No. Images are processed in-memory and deleted immediately.

How to handle errors?

The SDK result dictionary contains a 'success' boolean and an 'error' message if failed.

You May Also Like

Related tutorials, platform guides, and comparisons

Country Tutorial

Morocco Passport OCR with Python SDK

Use the official StructOCR Python SDK and FastAPI to extract structured MRZ and VIZ data from Morocco passports with a server-side integration.

Python · Passport
Country Tutorial

Chile Cédula OCR Python SDK

Python Tutorial: Automate KYC in Chile. Extract data from the Chilean Cédula de Identidad using StructOCR Python SDK. Supports RUN/RUT extraction and native Spanish text parsing.

Python · cédula de identidad
Country Tutorial

Australia Passport OCR with Python SDK

Use the official StructOCR Python SDK and FastAPI to extract structured MRZ and VIZ data from Australia passports with a server-side integration.

Python · Passport
Country Tutorial

Pakistan CNIC OCR Python SDK

Python Tutorial: Automate KYC in Pakistan. Extract data from CNIC using StructOCR Python SDK. Supports native text.

Python · cnic
Country Tutorial

Kazakhstan Passport OCR with Python SDK

Use the official StructOCR Python SDK and FastAPI to extract structured MRZ and VIZ data from Kazakhstan passports with a server-side integration.

Python · Passport
Country Tutorial

Spain Passport OCR with Python SDK

Use the official StructOCR Python SDK and FastAPI to extract structured MRZ and VIZ data from Spain passports with a server-side integration.

Python · Passport
Country Tutorial

Italy Carta di Identità OCR Python SDK

Python Tutorial: Automate KYC in Italy. Extract data from Carta di Identità Elettronica (CIE) using StructOCR Python SDK. Supports native text, Codice Fiscale, and MRZ extraction.

Python · carta di identità
Country Tutorial

Malaysia MyKad OCR Python SDK

Python Tutorial: Automate KYC in Malaysia. Extract data from the Malaysian Identity Card (MyKad) using StructOCR Python SDK. Supports NRIC extraction and multi-line address parsing.

Python · mykad
Country Tutorial

Kazakhstan Identity Card (Udostoverenie) OCR Python SDK

Python Tutorial: Automate KYC in Kazakhstan. Extract dual-script data, the 12-digit IIN, and validate TD1 MRZ from Identity Card (Udostoverenie) using StructOCR Python SDK.

Python · identity card (udostoverenie)
Country Tutorial

Indonesia KTP (e-KTP) OCR Python SDK

Python Tutorial: Automate KYC in Indonesia. Extract data from KTP (e-KTP) using StructOCR Python SDK. Supports native text.

Python · ktp (e-ktp)

Technical Comparisons & Integrations

Explore platform integrations and competitive analysis

From tutorial to production in 5 minutes.

You've seen the code. Now get your API key, grab your 200 free credits, and see it work with your own images. No credit card required.

Instant Access Cancel Anytime 99.9% Uptime