Introduction to the python API

kraken provides a powerful python API for programmatic access to all its functionality. This guide provides a basic introduction to the most important parts of the API.

High-Level API

The easiest way to use kraken programmatically is through the high-level API in the kraken.tasks module. This API provides a set of task-oriented classes for segmentation, recognition, and forced alignment.

Segmentation

To segment an image, you can use the SegmentationTaskModel class. It returns a Segmentation object containing the segmentation results.

The lines within the Segmentation object can be of two types, depending on the model used:

  • BaselineLine for models that output baselines and polygons.

  • BBoxLine for models that output bounding boxes.

from PIL import Image
from kraken.tasks import SegmentationTaskModel
from kraken.configs import SegmentationInferenceConfig

# Load the default segmentation model
model = SegmentationTaskModel.load_model()

im = Image.open('image.png')

config = SegmentationInferenceConfig()

segmentation = model.predict(im, config)

for line in segmentation.lines:
    print(line.baseline)

Recognition

To recognize the text in an image, you can use the RecognitionTaskModel class. This class takes a Segmentation object, a PIL image, and a configuration as inputs and returns an iterator of ocr_record objects.

Similar to segmentation, the returned records can be of two types:

from PIL import Image
from kraken.tasks import RecognitionTaskModel
from kraken.configs import RecognitionInferenceConfig

# Load a recognition model
model = RecognitionTaskModel.load_model('model.safetensors')

im = Image.ope('image.png')

config = RecognitionInferenceConfig()

# segmentation is a Segmentation object created by loading an XML file o
# running segmentation manually.
for record in model.predict(im, segmentation, config):
    print(record.prediction)

Forced Alignment

Forced alignment is the process of aligning a given transcription to the output of a text recognition model, producing approximate character locations. This is a specialized operation outside a normal ATR workflow and can be used, e.g., to produce word bounding boxes for a known good transcription.

You can use the ForcedAlignmentTaskModel class to perform forced alignment:

from PIL import Image
from kraken.tasks import ForcedAlignmentTaskModel
from kraken.containers import Segmentation, BaselineLine
from kraken.configs import RecognitionInferenceConfig

# `model.safetensor` is a recognition model
model = ForcedAlignmentTaskModel.load_model('model.safetensor')
im = Image.open('image.png')
line = BaselineLine(baseline=[(0,0), (100,0)], boundary=[(0,-10), (100,-10), (100,10), (0,10)], text='Hello World')
segmentation = Segmentation(lines=[line])
config = RecognitionInferenceConfig()

aligned_segmentation = model.predict(im, segmentation, config)
record = aligned_segmentation.lines[0]
print(record.prediction)
print(record.cuts)

Parsing XML

kraken can parse ALTO and PageXML files into Segmentation objects. This is useful for loading ground truth data or the results of other OCR engines. The XMLPage class handles this.

Note

The parser has been refactored in kraken 7.0 with changes to reading order parsing and robustness improvements. In particular, if the XML dimension field is invalid, kraken falls back to reading the source image to determine dimensions.

from kraken.lib.xml import XMLPage

xml_page = XMLPage('input.xml')
segmentation = xml_page.to_container()

Serialization

After segmentation and recognition, you can serialize the results into various formats, such as ALTO or PageXML, with the kraken.serialization.serialize() function.

from kraken.serialization import serialize

# Assume `segmentation` is a Segmentation object from a previous step
# and `im` is the PIL image object.

# Serialize to ALTO
alto_xml = serialize(segmentation, image_size=im.size, template='alto')

with open('output.alto.xml', 'w') as f:
    f.write(alto_xml)

# Serialize to PageXML
page_xml = serialize(segmentation, image_size=im.size, template='page')

with open('output.page.xml', 'w') as f:
    f.write(page_xml)

Plugin System

kraken can integrate new machine learning models through a plugin system. A plugin is a normal python package. Its entry points, declared in pyproject.toml or setup.cfg, tell kraken which classes to import for model loading, training, and configuration.

Entry Point Groups

Only kraken.models is required for a plugin whose model is loaded from safetensors for inference. The remaining groups are used by the optional extensions below.

Entry point group

kraken.models

Enables loading a model from safetensors weights files. The entry point key is the model’s Python class name.

kraken.lightning_modules

Used to identify the trainer that can load a checkpoint for conversion or continued training.

kraken.archs.recognition

Used to select a recognition trainer in ketos train and ketos test. The entry point key is the architecture name used with --arch.

kraken.archs.segmentation

Used to select a segmentation trainer in ketos segtrain. The entry point key is the architecture name used with --arch.

kraken.configs

Makes custom inference configs discoverable by kraken options and lets kraken load training and data configs stored in checkpoints.

Minimal Recognition Plugin

This minimal plugin implements the recognition model interface and registers the model class for loading by kraken ocr. The package contains the model implementation and the package metadata.

example-ocr/
    example_ocr/
        __init__.py
    pyproject.toml

Recognition models inherit from RecognitionBaseModel. In example_ocr/__init__.py, ExampleRecognizer also inherits from torch.nn.Module for PyTorch state handling. Plugins can use another library for model computation and wrap it in a PyTorch module for safetensors loading.

These attributes describe how kraken loads and runs the model.

  • model_type must include 'recognition' so the model can be selected for OCR.

  • _kraken_min_version specifies the oldest kraken version that can load the model.

  • seg_type can be set to 'bbox' or 'baselines' when the model expects a particular type of line segmentation.

  • user_metadata holds any JSON-serializable constructor arguments needed to rebuild the model before its weights are loaded.

Kraken calls prepare_for_inference(config) to apply the inference settings. It then calls predict(im, segmentation) with a PIL image and a Segmentation. The recognizer yields one OCR record per input line, a BBoxOCRRecord for this example.

For segmentation, kraken.models.base provides SegmentationBaseModel, whose predict(im) method returns a Segmentation.

from torch import nn

from kraken.containers import BBoxOCRRecord
from kraken.models.base import RecognitionBaseModel


class ExampleRecognizer(nn.Module, RecognitionBaseModel):
    _kraken_min_version = '7.1.0'
    model_type = ['recognition']
    seg_type = 'bbox'

    def __init__(self, character='x', **kwargs):
        super().__init__()
        self.user_metadata = {'character': character}

    def prepare_for_inference(self, config):
        self.eval()

    def predict(self, im, segmentation):
        for line in segmentation.lines:
            x0, y0, x1, y1 = line.bbox
            cut = ((x0, y0), (x1, y0), (x1, y1), (x0, y1))
            yield BBoxOCRRecord(self.user_metadata['character'], [cut], [1.0], line)

Register ExampleRecognizer under kraken.models in pyproject.toml. Kraken stores the class name in the weights file and uses it as the entry point key when loading the model. The key must be unique among installed kraken.models entries.

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "example-ocr"
version = "0.1.0"
dependencies = ["kraken>=7.1"]

[project.entry-points."kraken.models"]
ExampleRecognizer = "example_ocr:ExampleRecognizer"

Running the Example

PyTorch models that implement BaseModel can be exported to safetensors with write_safetensors(), including models trained outside ketos. The loader uses the registered class and the saved user_metadata to reconstruct the model and restore its state.

After installing the package with python -m pip install ., the example weights file can be created as follows.

from example_ocr import ExampleRecognizer
from kraken.models import write_safetensors

write_safetensors([ExampleRecognizer()], 'example.safetensors')

When the weights file is passed to kraken ocr, the installed model class is picked up automatically. The following command treats line.png as a single line and writes the example prediction x to out.txt.

$ kraken -i line.png out.txt ocr --no-segmentation -m example.safetensors

Optional Extensions

Model-Specific Inference Options

Model-specific settings such as a detection threshold or language hint are declared in a subclass of RecognitionInferenceConfig or SegmentationInferenceConfig. Models using the standard settings can leave inference_config_cls at its default, None.

The example recognizer adds a confidence field in ExampleRecognitionConfig and declares that class on the model. Give each field a default because kraken discovers the supported options by constructing the config without arguments.

...
from kraken.configs import RecognitionInferenceConfig


class ExampleRecognitionConfig(RecognitionInferenceConfig):
    def __init__(self, **kwargs):
        self.confidence = kwargs.pop('confidence', 1.0)
        super().__init__(**kwargs)

class ExampleRecognizer(nn.Module, RecognitionBaseModel):
    _kraken_min_version = '7.1.0'
    model_type = ['recognition']
    seg_type = 'bbox'

    inference_config_cls = ExampleRecognitionConfig
...

Kraken passes the model’s config to prepare_for_inference(). Read config.confidence there and use the value in the OCR record in place of the fixed 1.0. Users can change it with kraken ocr -O confidence=0.5 or with extra_options={'confidence': 0.5} on the API config (see Model-Specific Options).

To make the config discoverable by kraken options without a model file, add an optional entry under kraken.configs.

[project.entry-points."kraken.configs"]
ExampleRecognitionConfig = "example_ocr:ExampleRecognitionConfig"

Training with Existing ketos Commands

ketos handles training, saving checkpoints, and exporting the best model. A plugin can reuse that workflow by supplying a KrakenTrainerModule subclass, a model, a data module, and their config classes. The trainer base class extends LightningModule, whose guide explains the training, validation, and test hooks.

Trainers need to be registered as entry points in kraken.archs.recognition for ketos train and ketos test or kraken.archs.segmentation for ketos segtrain. Segmentation testing is specific to the BLLA segmenter right now.

The line-ocr scaffolds show how to connect a PyTorch model, LineOCRModel, to a dataset, LineDataset, and supply the model’s loss and decoding logic.

Training and Data Configs

ketos uses separate configs for the trainer and its data module. For recognition, subclass TrainingConfig and RecognitionTrainingDataConfig, respectively. For segmentation, use SegmentationTrainingDataConfig as the data config base.

line-ocr adds ctc_weight to the trainer config and max_line_width to the data config. The base classes in kraken.configs supply shared fields such as lrate, batch_size, and the input file lists.

from kraken.configs import RecognitionTrainingDataConfig, TrainingConfig


class LineOCRTrainingConfig(TrainingConfig):
    def __init__(self, **kwargs):
        self.ctc_weight = kwargs.pop('ctc_weight', 0.3)
        super().__init__(**kwargs)


class LineOCRDataConfig(RecognitionTrainingDataConfig):
    bidi_reordering = False

    def __init__(self, **kwargs):
        self.max_line_width = kwargs.pop('max_line_width', 2048)
        super().__init__(**kwargs)

ketos discovers custom options on instances constructed without arguments, so each option needs a default and an instance attribute.

Datasets and Data Loaders

ketos expands file arguments and manifests into the data config’s training_data, evaluation_data, and test_data lists. The LightningDataModule uses those paths to build datasets and provide batches to the trainer. In this example, the plugin supplies a PyTorch dataset called LineDataset to read the files.

from lightning import LightningDataModule
from torch.utils.data import DataLoader, random_split

from .dataset import LineDataset


class LineOCRDataModule(LightningDataModule):
    def __init__(self, data_config):
        super().__init__()
        self.save_hyperparameters()

    def setup(self, stage):
        config = self.hparams.data_config
        if stage == 'fit':
            train_set = self._dataset(config.training_data)
            if config.evaluation_data:
                self.train_set = train_set
                self.val_set = self._dataset(config.evaluation_data)
            else:
                self.train_set, self.val_set = random_split(
                    train_set, [config.partition, 1 - config.partition]
                )
        elif stage == 'test':
            self.test_set = self._dataset(config.test_data)

    def _dataset(self, paths):
        config = self.hparams.data_config
        return LineDataset(paths, max_line_width=config.max_line_width)

    def _loader(self, dataset, shuffle=False):
        config = self.hparams.data_config
        return DataLoader(dataset, batch_size=config.batch_size, shuffle=shuffle,
                          num_workers=config.num_workers)

    def train_dataloader(self):
        return self._loader(self.train_set, shuffle=True)

    def val_dataloader(self):
        return self._loader(self.val_set)

    def test_dataloader(self):
        return self._loader(self.test_set)
Trainer and Checkpoints

The KrakenTrainerModule subclass declares its task, the architecture name registered under kraken.archs.<task>, and the model, config, and data module classes used for training. Its constructor takes config and an optional model instance. Save config with save_hyperparameters() so the base class can store it in the checkpoint.

When loading a weights file, the base class finds an instance of _model_class and passes it to the constructor as model. Store the model as self.net so ketos can export it after training.

# line_ocr/training.py
from torch.optim import AdamW

from kraken.train.base import KrakenTrainerModule

from .configs import LineOCRDataConfig, LineOCRTrainingConfig
from .data import LineOCRDataModule
from .model import LineOCRModel


class LineOCRTrainer(KrakenTrainerModule):
    _task = 'recognition'
    _arch = 'line-ocr'
    _model_class = LineOCRModel
    _config_class = LineOCRTrainingConfig
    _data_config_class = LineOCRDataConfig
    _data_module_class = LineOCRDataModule
    _monitor = 'val_metric'

    def __init__(self, config, model=None):
        super().__init__()
        self.save_hyperparameters(ignore=['model'])
        self.net = model if model is not None else LineOCRModel()

    def training_step(self, batch, batch_idx):
        sequence_loss, ctc_loss = ...
        return sequence_loss + self.hparams.config.ctc_weight * ctc_loss

    def validation_step(self, batch, batch_idx):
        accuracy = ...
        self.log('val_metric', accuracy)

    def _save_checkpoint_extras(self, checkpoint):
        checkpoint['model_metadata'] = dict(self.net.user_metadata)

    def _build_net_from_checkpoint(self, checkpoint):
        return LineOCRModel(**checkpoint['model_metadata'])

    def test_step(self, batch, batch_idx):
        ...  # Accumulate test statistics.

    def on_test_epoch_end(self):
        self.test_metrics = ...  # Build a RecognitionTestMetrics instance.

During checkpoint loading, _build_net_from_checkpoint() reconstructs the model from the metadata written by _save_checkpoint_extras() before Lightning restores the weights.

By setting _monitor to the name of a validation metric the trainer logs to, the KrakenTrainerModule picks up which metric to use for early stopping when the quit attribute is set to early on the configuration object. With --quit early the base class then stops training once the metric has not improved by at least --min-delta for --lag validation runs. _monitor_mode selects whether higher ('max', the default) or lower ('min') values are better. Modules that leave _monitor unset do not support early stopping. To add other callbacks, override configure_callbacks() and extend the list returned by super().configure_callbacks().

The base class also implements optimizer_step() and lr_scheduler_step() for the schedules built by kraken.train.utils.configure_optimizer_and_lr_scheduler(). Trainers that return their own per-step schedulers from configure_optimizers() should override both methods.

For recognition testing, assign a RecognitionTestMetrics instance to self.test_metrics for the ketos report.

Registering and Running the Trainer

The model is registered under kraken.models for weights loading, as in the minimal plugin. Two entries point to the trainer. The architecture entry allows users to select it with --arch line-ocr, while the checkpoint entry lets ketos find it from the saved training config when reopening a checkpoint. Both saved config classes are registered under kraken.configs so they can be deserialized.

[project.entry-points."kraken.models"]
LineOCRModel = "line_ocr.model:LineOCRModel"

[project.entry-points."kraken.lightning_modules"]
LineOCRTrainer = "line_ocr.training:LineOCRTrainer"

[project.entry-points."kraken.archs.recognition"]
line-ocr = "line_ocr.training:LineOCRTrainer"

[project.entry-points."kraken.configs"]
LineOCRTrainingConfig = "line_ocr.configs:LineOCRTrainingConfig"
LineOCRDataConfig = "line_ocr.configs:LineOCRDataConfig"

Supply model-specific settings with -O key=value.

$ ketos train --arch line-ocr -t train.lst -e val.lst -O ctc_weight=0.5 -O max_line_width=1536

The same settings can be placed under train in an experiment file and passed with ketos --config experiment.yml train.

train:
  arch: line-ocr
  training_data: [train.lst]
  evaluation_data: [val.lst]
  ctc_weight: 0.5
  max_line_width: 1536

Low-Level API

For more fine-grained control, you can use the low-level API in the kraken.lib module. This API provides direct access to the core components of kraken, such as the neural network models and the CTC decoders.

For more information, please refer to the API Reference.