Yousef Gamal Romieh

Flutter Developer


Flutter OCR Identity Extractor

A comprehensive Flutter package for extracting text from images and parsing Saudi ID card data using Google ML Kit Text Recognition. This package provides OCR operations and comprehensive ID card data extraction with AI-powered confidence scoring.

Features

  • ✅ Extract text from images using Google ML Kit
  • ✅ Support for multiple recognition scripts
  • ✅ Combine results from different recognizers for better accuracy
  • ✅ Comprehensive Saudi ID card data extraction
  • ✅ AI-powered extraction with confidence scoring
  • ✅ Support for Arabic and English text
  • ✅ Arabic-Indic and Persian digits conversion
  • ✅ Hijri to Gregorian date conversion
  • ✅ Simple and easy-to-use API
  • ✅ Support for File, file path, and image bytes
  • ✅ Singleton pattern for efficient resource management

Installation

Add this to your package's pubspec.yaml file:

dependencies:
  flutter_ocr_identity_extractor: ^1.0.0

Then run:

flutter pub get

Platform Setup

Android

Add the following to your android/app/build.gradle:

android {
    defaultConfig {
        minSdkVersion 21
    }
}

iOS

Add the following to your ios/Podfile:

platform :ios, '10.0'

Then run:

cd ios && pod install

Usage

Basic OCR Usage

import 'package:flutter_ocr_identity_extractor/flutter_ocr_identity_extractor.dart';
import 'dart:io';

// Extract text from image file
final imageFile = File('/path/to/your/image.jpg');
final text = await OcrService.instance.recognizeTextFromImage(imageFile);

if (text != null) {
  print('Extracted text: $text');
} else {
  print('No text found in image');
}

Extract Saudi ID Card Data

import 'package:flutter_ocr_identity_extractor/flutter_ocr_identity_extractor.dart';
import 'dart:io';

// Step 1: Extract text from image
final imageFile = File('/path/to/id_card.jpg');
final ocrText = await OcrService.instance.recognizeTextFromImage(imageFile);

if (ocrText != null) {
  // Step 2: Parse ID card data
  final idData = SaudiIdParser.instance.parseOcrText(ocrText);
  
  print('Arabic Name: ${idData.arabicName}');
  print('English Name: ${idData.englishName}');
  print('Identity Number: ${idData.identityNumber}');
  print('Date of Birth: ${idData.dateOfBirth}');
  print('Gender: ${idData.gender}');
  print('Card Type: ${idData.cardType}');
}

AI-Powered Extraction with Confidence Scoring

import 'package:flutter_ocr_identity_extractor/flutter_ocr_identity_extractor.dart';

// Extract with AI-powered confidence scoring
final ocrText = await OcrService.instance.recognizeTextFromPath(imagePath);
if (ocrText != null) {
  final idData = await AiIdExtractor.instance.extractWithAi(ocrText);
  
  // idData contains extracted fields with high confidence
  // Smart name handling ensures both Arabic and English names are available
  print('Extracted ID Data: $idData');
  print('Arabic Name: ${idData.arabicName}'); // Always available if any name is found
  print('English Name: ${idData.englishName}'); // Always available if any name is found
}

Comprehensive Gender Detection (NEW in v1.2.0)

import 'package:flutter_ocr_identity_extractor/flutter_ocr_identity_extractor.dart';
import 'dart:io';

// Extract with comprehensive gender detection (text + image analysis)
final imageFile = File('/path/to/id_card.jpg');
final ocrText = await OcrService.instance.recognizeTextFromImage(imageFile);

if (ocrText != null) {
  // Use EnhancedIdExtractor for maximum accuracy
  final idData = await EnhancedIdExtractor.instance.extractWithComprehensiveGender(
    ocrText: ocrText,
    imageFile: imageFile, // Optional: enables image-based gender detection
  );
  
  // Gender detection uses multiple strategies:
  // 1. Name-based (بن/بنت)
  // 2. Text-based (ذكر/أنثى, Male/Female, M/F)
  // 3. Image-based (face analysis) - if imageFile provided
  print('Gender: ${idData.gender}'); // M or F with high confidence
}

Smart Name Handling (NEW in v1.2.0)

The package now automatically ensures both Arabic and English names are always available:

// Example 1: Only Arabic name found in OCR
// OCR Text: "محمد بن عبدالله الشمري"
final idData = await AiIdExtractor.instance.extractWithAi(ocrText);
print('Arabic: ${idData.arabicName}');  // "محمد بن عبدالله الشمري"
print('English: ${idData.englishName}'); // "Mohammed Bin Abdullah Alshammari" (auto-transliterated)

// Example 2: Only English name found in OCR
// OCR Text: "ALSHAMMARI, MOHAMMED ABDULLAH"
final idData2 = await AiIdExtractor.instance.extractWithAi(ocrText2);
print('Arabic: ${idData2.arabicName}');  // "محمد عبدالله الشمري" (auto-transliterated)
print('English: ${idData2.englishName}'); // "ALSHAMMARI, MOHAMMED ABDULLAH"

// Example 3: Both names found
// Both names are used as-is without transliteration

Complete Example

import 'package:flutter/material.dart';
import 'package:flutter_ocr_identity_extractor/flutter_ocr_identity_extractor.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class IdCardScannerExample extends StatefulWidget {
  @override
  _IdCardScannerExampleState createState() => _IdCardScannerExampleState();
}

class _IdCardScannerExampleState extends State<IdCardScannerExample> {
  SaudiIdData? _idData;
  bool _isProcessing = false;

  Future<void> _scanIdCard() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.camera);

    if (pickedFile != null) {
      setState(() {
        _isProcessing = true;
        _idData = null;
      });

      try {
        // Step 1: Extract text from image
        final ocrText = await OcrService.instance.recognizeTextFromPath(
          pickedFile.path,
        );

        if (ocrText == null || ocrText.isEmpty) {
          // Show error
          return;
        }

        // Step 2: Extract ID data with AI
        final idData = await AiIdExtractor.instance.extractWithAi(ocrText);

        setState(() {
          _isProcessing = false;
          _idData = idData;
        });
      } catch (e) {
        setState(() => _isProcessing = false);
        // Handle error
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('ID Card Scanner')),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
              onPressed: _isProcessing ? null : _scanIdCard,
              child: Text('Scan ID Card'),
            ),
            if (_isProcessing)
              CircularProgressIndicator()
            else if (_idData != null)
              _buildIdDataDisplay(_idData!),
          ],
        ),
      ),
    );
  }

  Widget _buildIdDataDisplay(SaudiIdData data) {
    return Padding(
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Arabic Name: ${data.arabicName ?? "N/A"}'),
          Text('English Name: ${data.englishName ?? "N/A"}'),
          Text('Identity Number: ${data.identityNumber ?? "N/A"}'),
          Text('Date of Birth: ${data.dateOfBirth ?? "N/A"}'),
          Text('Gender: ${data.gender ?? "N/A"}'),
        ],
      ),
    );
  }

  @override
  void dispose() {
    OcrService.instance.dispose();
    super.dispose();
  }
}

API Reference

OcrService

Singleton service for OCR operations.

Methods

  • recognizeTextFromImage(File imageFile) - Extract text from image file
  • recognizeTextFromPath(String imagePath) - Extract text from image path
  • recognizeTextFromBytes(InputImage inputImage) - Extract text from image bytes
  • dispose() - Dispose resources

SaudiIdParser

Parser for extracting Saudi ID card data from OCR text.

Methods

  • parseOcrText(String ocrText) - Parse OCR text and extract ID card data

Returns: SaudiIdData

AiIdExtractor

AI-powered extractor with confidence scoring.

Methods

  • extractWithAi(String ocrText) - Extract ID data with confidence scoring

Returns: Future<SaudiIdData>

SaudiIdData

Data class containing extracted ID card information:

  • arabicName - Arabic name
  • englishName - English name
  • identityNumber - 10-digit identity number
  • dateOfBirth - Date of birth (DD/MM/YYYY)
  • dateOfExpiry - Date of expiry
  • placeOfBirth - Place of birth
  • gender - Gender (M or F)
  • cardType - Type of ID card (citizen, resident, visitor)

Requirements

  • Flutter SDK: >=3.0.0
  • Dart SDK: >=3.0.0
  • Android: minSdkVersion 21
  • iOS: iOS 10.0+

Dependencies

  • google_mlkit_text_recognition: ^0.12.0
  • logger: ^2.6.1
  • arabic_name_transliterator: ^0.5.0

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

If you encounter any issues or have questions, please open an issue on the GitHub repository.


Yousef Gamal Romieh

Flutter Developer