Skip to main content

SDK oficial de Extraer Datos de INE — API de OCR para credenciales INE/IFE mexicanas (CURP, clave de elector, dirección y más).

Project description

extraer-datos-ine (Python)

SDK oficial en Python para la API de OCR para INE de Extraer Datos de INE — extrae CURP, nombre, clave de elector, dirección y todos los campos de una credencial para votar mexicana (INE/IFE) a partir de una imagen, en segundos.

  • 🇲🇽 Diseñado para credenciales INE e IFE (todos los modelos).
  • 🧩 Cero dependencias. Solo la librería estándar (urllib).
  • 🔠 Tipado (py.typed): IneData con los 20 campos y errores tipados.
  • 🐍 Compatible con Python 3.9+.

📚 Documentación de la API: https://extraerdatosdeine.com/docs 🔑 Consigue una API key con 20 extracciones gratis: https://extraerdatosdeine.com/register


Instalación

pip install extraer-datos-ine

Uso rápido

from extraer_datos_ine import IneExtractorClient

client = IneExtractorClient(api_key="ine_tu_api_key")

with open("ine_frente.jpg", "rb") as f:
    front = f.read()
with open("ine_reverso.jpg", "rb") as f:  # opcional, para CIC/OCR del reverso
    back = f.read()

result = client.extract(front=front, back=back)
print(result.data["curp"])          # 'PEGJ850101HDFRRL09'
print(result.data["claveElector"])  # 'PRGRJN85010109H100'
print(result.tokens_remaining)      # 19

Consultar saldo de tokens

print("Tokens disponibles:", client.get_balance())

Formas de enviar la imagen

El método de envío se elige automáticamente según el tipo de front/back.

Tipo de entrada Ejemplo Método HTTP usado
Binario bytes / bytearray multipart/form-data
Base64 "..." o {"base64": "..."} JSON base64
URL {"url": "https://..."} JSON URL (la API descarga la imagen)
# Binario
client.extract(front=front_bytes, front_mime_type="image/png")

# Base64
client.extract(front={"base64": b64}, back={"base64": back_b64})

# URL HTTPS
client.extract(front={"url": url}, back={"url": back_url})

front y back deben ser del mismo tipo: la API no mezcla métodos en una sola petición.

Manejo de errores

from extraer_datos_ine import IneExtractorError

try:
    result = client.extract(front=front)
except IneExtractorError as err:
    if err.code == "INSUFFICIENT_TOKENS":
        print("Sin tokens. Recarga en:", err.enroll_url)
    elif err.code == "LOW_IMAGE_QUALITY":
        print("Imagen ilegible. Campos faltantes:", err.missing_fields)
    else:
        print(f"[{err.code}] {err.message}")

Códigos de error

code HTTP Significado
MISSING_API_KEY 401 No se envió la API key
INVALID_API_KEY 401 API key inválida o revocada
MISSING_IMAGE 400 Falta la imagen frontal
INVALID_IMAGE_FORMAT 400 Formato no soportado (usa JPEG, PNG o WebP)
IMAGE_TOO_LARGE 400 La imagen excede 10 MB
INVALID_BASE64 400 Error al decodificar base64
INVALID_MULTIPART 400 Error al procesar el formulario multipart
URL_FETCH_FAILED 400 No se pudo descargar la imagen de la URL
URL_INVALID 400 URL inválida (debe ser HTTPS)
URL_BLOCKED 400 URL bloqueada por seguridad
URL_TIMEOUT 400 Timeout al descargar la imagen (10 s)
UNSUPPORTED_CONTENT_TYPE 415 Content-Type no soportado
INSUFFICIENT_TOKENS 402 Saldo insuficiente (ver err.enroll_url)
LOW_IMAGE_QUALITY 422 Imagen ilegible (ver err.missing_fields)
EXTRACTION_FAILED 500 Falló la extracción (el token se reembolsa)
PROCESSING_ERROR 500 Error procesando la imagen (token reembolsado)
INTERNAL_ERROR 500 Error interno del servidor
NETWORK_ERROR Fallo de red (lado del cliente)
TIMEOUT Se superó el timeout del cliente

Campos extraídos (IneData)

nombre, apellidoPaterno, apellidoMaterno, domicilio, calle, colonia, codigoPostal, municipio, estado, seccion, curp, claveElector, anioRegistro, fechaNacimiento, sexo, vigencia, numeroVertical, ocr, cic, emision.

Los cuatro últimos (numeroVertical, ocr, cic, emision) viven en el reverso: envía también back para obtenerlos.

Configuración del cliente

IneExtractorClient(
    api_key="ine_...",
    base_url="https://extraerdatosdeine.com/api/v1",  # default
    timeout=60.0,                                       # segundos
)

Desarrollo

python -m venv .venv && source .venv/bin/activate
pip install -e .
python -m unittest discover -s tests -v
pip install build && python -m build   # genera sdist + wheel en dist/

Enlaces

Licencia

MIT © Extraer Datos de INE

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

extraer_datos_ine-1.0.0.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

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

extraer_datos_ine-1.0.0-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file extraer_datos_ine-1.0.0.tar.gz.

File metadata

  • Download URL: extraer_datos_ine-1.0.0.tar.gz
  • Upload date:
  • Size: 9.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for extraer_datos_ine-1.0.0.tar.gz
Algorithm Hash digest
SHA256 1ac55bf7216efda7f5028f2290e28473ddbdf80cfddb46c87b1d09aaa70ebb59
MD5 8796a7f94ac3af8ef82b312333bc4d93
BLAKE2b-256 db9dc56b88a3f378160c86c1568bbcabcbcbf1d4985ca6c43c649c9eb2b84041

See more details on using hashes here.

File details

Details for the file extraer_datos_ine-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for extraer_datos_ine-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3c7677e8cbc01e424118c47b4539a5200d734b0819d94e775497e42ec8091a99
MD5 c155cf84b3716534940b350ec5b63429
BLAKE2b-256 0197e561c4b1715907ac898890ad77308b267ba82c5965b10c6ef7b2343f9a99

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