Skip to main content

Python library for reading Thai national ID cards using smartcard readers

Project description

pythaiidcard

Python library for reading Thai national ID cards using smartcard readers.

Thai ID Card Reader Demo

Table of Contents

Features

  • โœ… Full Card Data Extraction: Read all information from Thai ID cards
  • ๐Ÿ“ธ Photo Support: Extract and save card photos (JPEG format)
  • ๐Ÿ”’ Data Validation: Automatic CID checksum validation and date parsing
  • ๐Ÿ“… Date Conversion: Buddhist Era to Gregorian calendar conversion
  • ๐ŸŽจ Modern Web UI: Streamlit-based debug interfaces
  • ๐Ÿ Type-Safe: Full type hints and Pydantic models
  • ๐Ÿ” Error Handling: Comprehensive exception handling and system checks
  • ๐Ÿ“ฆ Zero Config: Auto-detects readers and connects to cards
  • ๐Ÿš€ Fast: Efficient APDU command implementation

Quick Start

# 1. Install system dependencies
sudo apt-get install -y pcscd libpcsclite-dev python3-dev swig

# 2. Install Python dependencies
uv sync --group dev

# 3. Run the web interface
uv run streamlit run debug/app_compact.py

Then open http://localhost:8501 in your browser, insert your Thai ID card, and click "Scan Readers" โ†’ "Connect" โ†’ "Read Card".

Credits

This project is inspired by and based on:

Prerequisites

System Dependencies

This project requires the following system packages:

  • pcscd - PC/SC Smart Card Daemon
  • libpcsclite-dev - PC/SC development files
  • python3-dev - Python development headers
  • swig - Interface compiler for Python bindings

Install them using:

sudo apt-get update
sudo apt-get install -y pcscd libpcsclite-dev python3-dev swig

Or if you have mise installed:

mise run install-deps

Installation

This project uses uv for Python package management.

# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install Python dependencies
uv sync

Or with mise:

mise run setup

Usage

Command Line

Connect your smartcard reader and insert a Thai ID card, then run:

uv run python thai-idcard.py

Or:

mise run run

The script will:

  • Detect available smartcard readers
  • Connect to the first reader automatically
  • Read personal data from the Thai ID card including:
    • Citizen ID
    • Thai/English full name
    • Date of birth
    • Gender
    • Card issuer
    • Issue/Expiry dates
    • Address
    • Photo (saved as {CID}.jpg)

Web Interface (Streamlit)

For a modern web-based interface with visual feedback:

# Compact modern interface (recommended)
uv run streamlit run debug/app_compact.py

# Full debug interface with logs
uv run streamlit run debug/app.py

Features:

  • ๐Ÿ” Visual reader detection and selection
  • ๐Ÿ”Œ Connection status monitoring
  • ๐Ÿ“– Interactive card reading with progress bars
  • ๐Ÿ“ธ Photo preview and download
  • ๐Ÿ’พ Export data as JSON, CSV, or photo
  • ๐Ÿ› Real-time debug logging (full interface)

See debug/README.md for detailed documentation.

Python Library

from pythaiidcard import ThaiIDCardReader

# Basic usage - auto-connect and read card
reader = ThaiIDCardReader()
with reader.card_session():
    card = reader.read_card(include_photo=True)

    print(f"Name: {card.english_fullname}")
    print(f"CID: {card.cid}")
    print(f"Age: {card.age}")
    print(f"Expires: {card.expire_date}")
    print(f"Valid: {not card.is_expired}")

    # Save photo
    if card.photo:
        card.save_photo()  # Saves as {cid}.jpg

# Advanced usage - manual control
from pythaiidcard.reader import ThaiIDCardReader

# List available readers
readers = ThaiIDCardReader.list_readers()
for reader_info in readers:
    print(f"Reader {reader_info.index}: {reader_info.name}")
    print(f"  ATR: {reader_info.atr}")
    print(f"  Connected: {reader_info.connected}")

# Connect to specific reader
reader = ThaiIDCardReader(reader_index=0)
reader.connect()

# Read without photo for faster operation
card = reader.read_card(include_photo=False)

# Read with progress callback
def on_photo_progress(current, total):
    print(f"Reading photo: {current}/{total}")

card = reader.read_card(
    include_photo=True,
    photo_progress_callback=on_photo_progress
)

reader.disconnect()

# Access card data
print(f"Thai Name: {card.thai_fullname}")
print(f"English Name: {card.english_fullname}")
print(f"Gender: {card.gender_text}")  # "Male" or "Female"
print(f"Address: {card.address}")
print(f"Issue Date: {card.issue_date}")
print(f"Days until expiry: {card.days_until_expiry}")

# Export as JSON
import json
card_json = card.model_dump_json(indent=2)
print(card_json)

Data Fields

The following information is extracted from the card:

Field Description
CID 13-digit citizen identification number
TH Fullname Full name in Thai
EN Fullname Full name in English
Date of birth Birth date
Gender Gender
Card Issuer Issuing organization
Issue Date Card issue date
Expire Date Card expiration date
Address Registered address
Photo JPEG photo (saved to file)

Dependencies

Python Packages

  • pyscard (>=2.3.0) - Python smartcard library for PC/SC interface
  • Pillow (>=11.3.0) - Python imaging library for photo handling
  • pydantic (>=2.0) - Data validation and settings management
  • python-dateutil (>=2.8.2) - Date parsing utilities

Development Dependencies

  • streamlit (>=1.28.0) - Web interface framework (optional)
  • ruff (>=0.8.4) - Linting and formatting

Troubleshooting

SystemDependencyError: Missing required system dependencies

The library will automatically check for required system dependencies on Linux systems with apt package manager. If dependencies are missing, you'll see a helpful error message with installation instructions.

Example error:

SystemDependencyError: Missing required system dependencies:

  โœ— PC/SC Smart Card Daemon (pcscd)
  โœ— PC/SC Lite development library (libpcsclite-dev)

To install missing dependencies, run:

  sudo apt-get update && sudo apt-get install -y pcscd libpcsclite-dev python3-dev swig

To skip the dependency check (if you know dependencies are installed via other means):

from pythaiidcard import ThaiIDCardReader

reader = ThaiIDCardReader(skip_system_check=True)

"No such file or directory: winscard.h"

Install the system dependencies listed above, particularly libpcsclite-dev.

"No readers available"

  • Ensure your smartcard reader is connected
  • Check that the pcscd service is running: sudo systemctl status pcscd
  • Start it if needed: sudo systemctl start pcscd

Permission denied

Add your user to the scard group:

sudo usermod -a -G scard $USER

Then log out and log back in.

Project Structure

pythaiidcard/
โ”œโ”€โ”€ pythaiidcard/              # Main library package
โ”‚   โ”œโ”€โ”€ __init__.py       # Package initialization
โ”‚   โ”œโ”€โ”€ reader.py         # ThaiIDCardReader implementation
โ”‚   โ”œโ”€โ”€ models.py         # Pydantic data models
โ”‚   โ”œโ”€โ”€ constants.py      # APDU commands and response codes
โ”‚   โ”œโ”€โ”€ exceptions.py     # Custom exceptions
โ”‚   โ”œโ”€โ”€ utils.py          # Utility functions
โ”‚   โ””โ”€โ”€ system_check.py   # System dependency checking
โ”œโ”€โ”€ debug/                # Debug interfaces
โ”‚   โ”œโ”€โ”€ app.py           # Full debug interface (multi-tab)
โ”‚   โ”œโ”€โ”€ app_compact.py   # Modern compact interface
โ”‚   โ”œโ”€โ”€ README.md        # Debug interface documentation
โ”‚   โ””โ”€โ”€ RUN_COMPACT.sh   # Quick launch script
โ”œโ”€โ”€ thai-idcard.py       # Legacy CLI script
โ”œโ”€โ”€ pyproject.toml       # Project configuration
โ””โ”€โ”€ README.md            # This file

Key Components

  • ThaiIDCardReader: Main class for reading Thai ID cards
  • ThaiIDCard: Pydantic model with validated card data
  • CardReaderInfo: Information about available card readers
  • System Check: Automatic validation of system dependencies
  • Debug Interfaces: Streamlit-based web UIs for testing and debugging

License

See LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pythaiidcard-0.1.0.tar.gz (3.9 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pythaiidcard-0.1.0-py3-none-any.whl (20.2 kB view details)

Uploaded Python 3

File details

Details for the file pythaiidcard-0.1.0.tar.gz.

File metadata

  • Download URL: pythaiidcard-0.1.0.tar.gz
  • Upload date:
  • Size: 3.9 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.5

File hashes

Hashes for pythaiidcard-0.1.0.tar.gz
Algorithm Hash digest
SHA256 017b997419e6cc3ac2f937a228b485524ef6f03893981088d0b5b8f2085620cb
MD5 3ada7457668cbbc97482391f4f7309f6
BLAKE2b-256 164e0fd059bb5ad9e12a8aad1c9d94e6c8a1f5f8a558bc7b0833d49a766e94db

See more details on using hashes here.

File details

Details for the file pythaiidcard-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pythaiidcard-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b2d08f4f7ef2a91118a44e96b0dc2504e0dae16c0e40ce921a0003ee305ef0db
MD5 b79d2763f29af443083f61b0c56a149a
BLAKE2b-256 4e949159f231c2712cc25a3cecc41d0c8619036ef18cbdb9a0449e43ae9f1e35

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page