Kervyn OCR 130M · Preview

Español   ·   English


Español

🔬 Preview. Es la primera versión pública del OCR de Kervyn y todavía está en desarrollo.

  • Funciona y está medido: las cifras de abajo son reales, con sus puntos flojos incluidos.
  • Los pesos pueden cambiar en próximas versiones. Para fijar esta, usa revision="v1".
  • Tu opinión nos ayuda a mejorarlo.

Kervyn OCR convierte páginas de documentos (PDF o imagen) en Markdown: títulos, párrafos en orden de lectura, listas, tablas y fórmulas.

  • Idiomas: español e inglés, en documento impreso o digital (no manuscrito).
  • Pequeño: 132,5 millones de parámetros; los pesos ocupan 530 MB. Funciona en CPU.
  • Un solo modelo para todo: el mismo modelo encuentra las regiones de la página (11 clases) y lee cada una según lo que es: texto, tabla (Markdown, o HTML si hay celdas combinadas) o fórmula (LaTeX).
  • Modelo propio, de cero: arquitectura, tokenizer y pesos de Kervyn, entrenados desde cero. No deriva de ningún otro modelo.
  • Licencia Apache-2.0.

Qué tal lee

El error es la distancia de edición normalizada (NED) entre lo leído y el texto de referencia, medida párrafo a párrafo: 0 es perfecto y 0,01 es una letra mal de cada cien. Ninguna de estas páginas se usó para entrenar.

Documentos oficiales, frente a dos OCR abiertos mucho mayores (20 páginas por grupo; el BOE es de 2025 y los actos de la UE van a dos columnas):

Kervyn OCR (0,13 B) GLM-OCR (0,9 B) PaddleOCR-VL (0,9 B)
BOE 0,0043 0,0039 0,0033
Diario Oficial de la UE, español 0,0051 0,0046 0,0243
Diario Oficial de la UE, inglés 0,0046 0,0046 0,0139

Con la séptima parte de parámetros queda a su altura en estas páginas. Son 20 páginas por grupo: las diferencias pequeñas no son significativas.

Más español (error medio / mediano):

Conjunto Páginas Error Párrafos leídos sin un solo fallo
Boletines autonómicos (Madrid, Murcia) 11 0,0007 / 0,0003 175 de 185
Actos de la UE, páginas completas 40 0,0041 / 0,0019 —
Artículos de Wikipedia para imprimir 41 0,025 / 0,002 185 de 263

Otros tipos de documento, en inglés (muestra fija de 282 páginas de OmniDocBench, 40 por tipo; error medio / mediano de los párrafos de texto y páginas por debajo de 0,05):

Tipo Error Páginas bien leídas
Artículos científicos 0,027 / 0,005 33 de 34
Libros 0,060 / 0,015 24 de 31
Diapositivas 0,020 / 0,006 28 de 33
Revistas 0,062 / 0,011 32 de 39
Exámenes 0,135 / 0,028 22 de 34
Periódicos 0,128 / 0,049 21 de 40
Libros de texto en color 0,157 / 0,054 16 de 35

Tablas y fórmulas:

  • Tablas del BOE de 2025 (60): TEDS 0,980; las sencillas, 1,000; las de celdas combinadas, 0,87.
  • Fórmulas sueltas (560 de la misma muestra de OmniDocBench): lee bien el 61 % (NED del LaTeX por debajo de 0,3) y clava el 13 %.

Limitaciones

  • Fórmulas dentro del texto: las escribe casi siempre como caracteres sueltos, no en LaTeX. Las fórmulas sueltas sí salen en LaTeX, con la calidad de arriba.
  • Maquetaciones difíciles: periódicos, exámenes y libros de texto en color pierden párrafos. Cuando el texto rodea una foto puede perder alguno.
  • Logotipos y sellos: a veces los «lee» como texto que no está.
  • No lee manuscrito ni otros alfabetos (cirílico, chino, árabe…).
  • Velocidad en CPU: de 20 a 30 segundos por página con 6 hilos. No está optimizado todavía.

Uso

pip install torch numpy pillow pymupdf tokenizers safetensors pyyaml huggingface_hub
import sys
from huggingface_hub import snapshot_download

folder = snapshot_download("Kervyn-AI/Kervyn-OCR-130M-Preview", revision="v1")
sys.path.insert(0, folder)
from kervyn_ocr import KervynOCR

ocr = KervynOCR.load(folder)                 # usa la GPU si la hay; si no, la CPU
print(ocr.markdown("documento.pdf"))         # todo el documento, en Markdown

for page in ocr.pages("documento.pdf", pages=[0]):
    for block in page.blocks:                # clase, caja en píxeles (150 ppp) y lo leído
        print(block.kind, block.box, block.text[:60])

También desde la línea de órdenes, dentro de la carpeta descargada:

python ocr.py informe.pdf pagina.png --out salida/ --json
  • Entrada: PDF (se pinta a 150 ppp) o imágenes de página. De una imagen se supone que es una hoja entera; si no lo es, indica su resolución con image_dpi.
  • Salida: Markdown; con --json, además las regiones de cada página con su clase, su caja y la seguridad de la lectura.
  • Cabeceras y pies de página no se copian. Las figuras dejan una marca, sin descripción.

Cómo está hecho

  • Codificador de imagen propio (transformer con tallo convolucional) y decodificador de 12 capas, con el tokenizer de Kervyn ampliado con marcas para tablas, regiones y posiciones.
  • Dos pasos por página: primero la maquetación (la página a baja resolución da sus regiones en orden de lectura) y después la lectura de cada región a su resolución.
  • Datos de entrenamiento: páginas del BOE y del Diario Oficial de la UE con su capa de texto, DocLayNet (maquetación y lectura), UniMER (fórmulas) y texto, tablas y páginas pintados al vuelo con tipografías libres. OmniDocBench y los conjuntos de arriba solo se usan para medir.

English

🔬 Preview. This is the first public version of Kervyn's OCR and it is still in development.

  • It works and it is measured: the figures below are real, weak spots included.
  • Weights may change in later versions. To pin this one, use revision="v1".
  • Your feedback helps us improve it.

Kervyn OCR turns document pages (PDF or image) into Markdown: headings, paragraphs in reading order, lists, tables and formulas.

  • Languages: Spanish and English, printed or digital documents (no handwriting).
  • Small: 132.5 million parameters; the weights take 530 MB. It runs on CPU.
  • One model for everything: the same model finds the regions of the page (11 classes) and reads each one as what it is: text, table (Markdown, or HTML when cells are merged) or formula (LaTeX).
  • Own model, from scratch: Kervyn's architecture, tokenizer and weights, trained from scratch. It does not derive from any other model.
  • Apache-2.0 license.

How well it reads

The error is the normalised edit distance (NED) between the reading and the reference text, measured paragraph by paragraph: 0 is perfect and 0.01 is one wrong character in a hundred. None of these pages was used for training.

Official documents, against two much larger open OCR models (20 pages per group; the BOE is the Spanish official gazette, 2025 issues; EU acts are set in two columns):

Kervyn OCR (0.13 B) GLM-OCR (0.9 B) PaddleOCR-VL (0.9 B)
BOE 0.0043 0.0039 0.0033
EU Official Journal, Spanish 0.0051 0.0046 0.0243
EU Official Journal, English 0.0046 0.0046 0.0139

With one seventh of the parameters it is on a par with them on these pages. There are 20 pages per group: small differences are not significant.

More Spanish (mean / median error):

Set Pages Error Paragraphs read without a single mistake
Regional gazettes (Madrid, Murcia) 11 0.0007 / 0.0003 175 of 185
EU acts, whole pages 40 0.0041 / 0.0019 —
Wikipedia articles, print version 41 0.025 / 0.002 185 of 263

Other document types, in English (fixed sample of 282 OmniDocBench pages, 40 per type; mean / median error of text paragraphs and pages below 0.05):

Type Error Pages read well
Scientific articles 0.027 / 0.005 33 of 34
Books 0.060 / 0.015 24 of 31
Slides 0.020 / 0.006 28 of 33
Magazines 0.062 / 0.011 32 of 39
Exam papers 0.135 / 0.028 22 of 34
Newspapers 0.128 / 0.049 21 of 40
Colour textbooks 0.157 / 0.054 16 of 35

Tables and formulas:

  • Tables from the 2025 BOE (60): TEDS 0.980; simple ones 1.000; with merged cells 0.87.
  • Display formulas (560 from the same OmniDocBench sample): 61 % are read well (LaTeX NED below 0.3) and 13 % exactly.

Limitations

  • Inline formulas: it mostly writes them as plain characters, not LaTeX. Display formulas do come out in LaTeX, with the quality above.
  • Hard layouts: newspapers, exam papers and colour textbooks lose paragraphs. Text that wraps around a picture may lose one.
  • Logos and stamps: it sometimes "reads" them as text that is not there.
  • No handwriting and no other scripts (Cyrillic, Chinese, Arabic…).
  • CPU speed: 20 to 30 seconds per page on 6 threads. It is not optimised yet.

Usage

pip install torch numpy pillow pymupdf tokenizers safetensors pyyaml huggingface_hub
import sys
from huggingface_hub import snapshot_download

folder = snapshot_download("Kervyn-AI/Kervyn-OCR-130M-Preview", revision="v1")
sys.path.insert(0, folder)
from kervyn_ocr import KervynOCR

ocr = KervynOCR.load(folder)                 # uses the GPU if there is one, otherwise the CPU
print(ocr.markdown("document.pdf"))          # the whole document, in Markdown

for page in ocr.pages("document.pdf", pages=[0]):
    for block in page.blocks:                # class, box in pixels (150 dpi) and the reading
        print(block.kind, block.box, block.text[:60])

Or from the command line, inside the downloaded folder:

python ocr.py report.pdf page.png --out out/ --json
  • Input: PDF (rendered at 150 dpi) or page images. An image is assumed to be a whole sheet; if it is not, give its resolution with image_dpi.
  • Output: Markdown; with --json, also the regions of each page with class, box and reading confidence.
  • Page headers and footers are not copied. Figures leave a mark, without a description.

How it is built

  • Own image encoder (transformer with a convolutional stem) and a 12-layer decoder, with Kervyn's tokenizer extended with marks for tables, regions and positions.
  • Two steps per page: first the layout (the page at low resolution gives its regions in reading order), then the reading of each region at its own resolution.
  • Training data: pages of the BOE and of the EU Official Journal with their text layer, DocLayNet (layout and reading), UniMER (formulas), and text, tables and pages rendered on the fly with free fonts. OmniDocBench and the sets above are used only for measuring.
Downloads last month
42
Safetensors
Model size
0.1B params
Tensor type
F32
·
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Datasets used to train Kervyn-AI/Kervyn-OCR-130M-Preview