API reference

kraken.binarization module

kraken.binarization

An adaptive binarization algorithm.

kraken.binarization.nlbin(im: PIL.Image.Image, threshold: float = 0.5, zoom: float = 0.5, escale: float = 1.0, border: float = 0.1, perc: int = 80, range: int = 20, low: int = 5, high: int = 90)<module ‘PIL.Image’ from ‘/home/mittagessen/.miniconda3/envs/ta/lib/python3.7/site-packages/PIL/Image.py’>

Performs binarization using non-linear processing.

Parameters
  • im (PIL.Image.Image) –

  • threshold (float) –

  • zoom (float) – Zoom for background page estimation

  • escale (float) – Scale for estimating a mask over the text region

  • border (float) – Ignore this much of the border

  • perc (int) – Percentage for filters

  • range (int) – Range for filters

  • low (int) – Percentile for black estimation

  • high (int) – Percentile for white estimation

Returns

PIL.Image containing the binarized image

Raises

KrakenInputException when trying to binarize an empty image.

kraken.serialization module

kraken.serialization.render_report(model: str, chars: int, errors: int, char_confusions: collections.Counter, scripts: collections.Counter, insertions: collections.Counter, deletions: int, substitutions: collections.Counter)str

Renders an accuracy report.

Parameters
  • model (str) – Model name.

  • errors (int) – Number of errors on test set.

  • char_confusions (dict) – Dictionary mapping a tuple (gt, pred) to a number of occurrences.

  • scripts (dict) – Dictionary counting character per script.

  • insertions (dict) – Dictionary counting insertion operations per Unicode script

  • deletions (int) – Number of deletions

  • substitutions (dict) – Dictionary counting substitution operations per Unicode script.

Returns

A string containing the rendered report.

kraken.serialization.serialize(records: Sequence[kraken.rpred.ocr_record], image_name: Optional[str] = None, image_size: Tuple[int, int] = (0, 0), writing_mode: str = 'horizontal-tb', scripts: Optional[Iterable[str]] = None, regions: Optional[Dict[str, List[List[Tuple[int, int]]]]] = None, template: str = 'hocr')str

Serializes a list of ocr_records into an output document.

Serializes a list of predictions and their corresponding positions by doing some hOCR-specific preprocessing and then renders them through one of several jinja2 templates.

Note: Empty records are ignored for serialization purposes.

Parameters
  • records (iterable) – List of kraken.rpred.ocr_record

  • image_name (str) – Name of the source image

  • image_size (tuple) – Dimensions of the source image

  • writing_mode (str) – Sets the principal layout of lines and the direction in which blocks progress. Valid values are horizontal-tb, vertical-rl, and vertical-lr.

  • scripts (list) – List of scripts contained in the OCR records

  • regions (list) – Dictionary mapping region types to a list of region polygons.

  • template (str) – Selector for the serialization format. May be ‘hocr’ or ‘alto’.

Returns

(str) rendered template.

kraken.blla module

Note

blla provides the interface to the fully trainable segmenter. For the legacy segmenter interface refer to the pageseg module. Note that recognition models are not interchangeable between segmenters.

kraken.blla

Trainable baseline layout analysis tools for kraken

kraken.blla.segment(im, text_direction: str = 'horizontal-lr', mask: Optional[numpy.array] = None, reading_order_fn: Callable = <function polygonal_reading_order>, model: Optional[Union[List[kraken.lib.vgsl.TorchVGSLModel], kraken.lib.vgsl.TorchVGSLModel]] = None, device: str = 'cpu')

Segments a page into text lines using the baseline segmenter.

Segments a page into text lines and returns the polyline formed by each baseline and their estimated environment.

Parameters
  • im (PIL.Image) – An RGB image.

  • text_direction (str) – Ignored by the segmenter but kept for serialization.

  • mask (PIL.Image) – A bi-level mask image of the same size as im where 0-valued regions are ignored for segmentation purposes. Disables column detection.

  • reading_order_fn (function) – Function to determine the reading order. Has to accept a list of tuples (baselines, polygon) and a text direction (lr or rl).

  • model (vgsl.TorchVGSLModel or list) – One or more TorchVGSLModel containing a segmentation model. If none is given a default model will be loaded.

  • device (str or torch.Device) – The target device to run the neural network on.

Returns

‘$dir’,

’type’: ‘baseline’, ‘lines’: [

{‘baseline’: [[x0, y0], [x1, y1], …, [x_n, y_n]], ‘boundary’: [[x0, y0, x1, y1], … [x_m, y_m]]}, {‘baseline’: [[x0, …]], ‘boundary’: [[x0, …]]}

] ‘regions’: [

{‘region’: [[x0, y0], [x1, y1], …, [x_n, y_n]], ‘type’: ‘image’}, {‘region’: [[x0, …]], ‘type’: ‘text’}

]

}: A dictionary containing the text direction and under the key ‘lines’ a list of reading order sorted baselines (polylines) and their respective polygonal boundaries. The last and first point of each boundary polygon is connected.

Return type

{‘text_direction’

Raises
  • KrakenInputException if the input image is not binarized or the text

  • direction is invalid.

kraken.pageseg module

Note

pageseg is the legacy bounding box-based segmenter. For the trainable baseline segmenter interface refer to the blla module. Note that recognition models are not interchangeable between segmenters.

kraken.pageseg

Layout analysis and script detection methods.

kraken.pageseg.segment(im, text_direction: str = 'horizontal-lr', scale: Optional[float] = None, maxcolseps: float = 2, black_colseps: bool = False, no_hlines: bool = True, pad: int = 0, mask: Optional[numpy.array] = None, reading_order_fn: Callable = <function reading_order>)Dict[str, Any]

Segments a page into text lines.

Segments a page into text lines and returns the absolute coordinates of each line in reading order.

Parameters
  • im (PIL.Image) – A bi-level page of mode ‘1’ or ‘L’

  • text_direction (str) – Principal direction of the text (horizontal-lr/rl/vertical-lr/rl)

  • scale (float) – Scale of the image

  • maxcolseps (int) – Maximum number of whitespace column separators

  • black_colseps (bool) – Whether column separators are assumed to be vertical black lines or not

  • no_hlines (bool) – Switch for horizontal line removal

  • pad (int or tuple) – Padding to add to line bounding boxes. If int the same padding is used both left and right. If a 2-tuple, uses (padding_left, padding_right).

  • mask (PIL.Image) – A bi-level mask image of the same size as im where 0-valued regions are ignored for segmentation purposes. Disables column detection.

  • reading_order_fn (Callable) – Function to call to order line output. Callable accepting a list of slices (y, x) and a text direction in (rl, lr).

Returns

‘$dir’, ‘boxes’: [(x1, y1, x2, y2),…]}: A dictionary containing the text direction and a list of reading order sorted bounding boxes under the key ‘boxes’.

Return type

{‘text_direction’

Raises
  • KrakenInputException if the input image is not binarized or the text

  • direction is invalid.

kraken.rpred module

kraken.rpred

Generators for recognition on lines images.

kraken.rpred.bidi_record(record: kraken.rpred.ocr_record, base_dir=None)kraken.rpred.ocr_record

Reorders a record using the Unicode BiDi algorithm.

Models trained for RTL or mixed scripts still emit classes in LTR order requiring reordering for proper display.

Parameters

record (kraken.rpred.ocr_record) –

Returns

kraken.rpred.ocr_record

class kraken.rpred.mm_rpred(nets: Dict[str, kraken.lib.models.TorchSeqRecognizer], im: PIL.Image.Image, bounds: dict, pad: int = 16, bidi_reordering: Union[bool, str] = True, script_ignore: Optional[List[str]] = None)

Bases: object

Multi-model version of kraken.rpred.rpred

class kraken.rpred.ocr_record(prediction: str, cuts, confidences: List[float], line: Union[List, Dict[str, List]])

Bases: object

A record object containing the recognition result of a single line

kraken.rpred.rpred(network: kraken.lib.models.TorchSeqRecognizer, im: PIL.Image.Image, bounds: dict, pad: int = 16, bidi_reordering: Union[bool, str] = True)Generator[kraken.rpred.ocr_record, None, None]

Uses a TorchSeqRecognizer and a segmentation to recognize text

Parameters
  • network (kraken.lib.models.TorchSeqRecognizer) – A TorchSegRecognizer object

  • im (PIL.Image.Image) – Image to extract text from

  • bounds (dict) – A dictionary containing a ‘boxes’ entry with a list of coordinates (x0, y0, x1, y1) of a text line in the image and an entry ‘text_direction’ containing ‘horizontal-lr/rl/vertical-lr/rl’.

  • pad (int) – Extra blank padding to the left and right of text line. Auto-disabled when expected network inputs are incompatible with padding.

  • bidi_reordering (bool|str) – Reorder classes in the ocr_record according to the Unicode bidirectional algorithm for correct display. Set to L|R to change base text direction.

Yields

An ocr_record containing the recognized text, absolute character positions, and confidence values for each character.

kraken.transcribe module

Utility functions for ground truth transcription.

kraken.linegen module

kraken.lib.models module

kraken.lib.models

Wrapper around TorchVGSLModel including a variety of forward pass helpers for sequence classification.

class kraken.lib.models.TorchSeqRecognizer(nn, decoder=<function greedy_decoder>, train: bool = False, device: str = 'cpu')

Bases: object

A class wrapping a TorchVGSLModel with a more comfortable recognition interface.

forward(line: torch.Tensor, lens: Optional[torch.Tensor] = None)numpy.array

Performs a forward pass on a torch tensor of one or more lines with shape (N, C, H, W) and returns a numpy array (N, W, C).

Parameters
  • line (torch.Tensor) – NCHW line tensor

  • lens (torch.Tensor) – Optional tensor containing sequence lengths if N > 1

Returns

Tuple with (N, W, C) shaped numpy array and final output sequence lengths.

predict(line: torch.Tensor, lens: Optional[torch.Tensor] = None)List[List[Tuple[str, int, int, float]]]

Performs a forward pass on a torch tensor of a line with shape (N, C, H, W) and returns the decoding as a list of tuples (string, start, end, confidence).

Parameters
  • line (torch.Tensor) – NCHW line tensor

  • lens (torch.Tensor) – Optional tensor containing sequence lengths if N > 1

Returns

List of decoded sequences.

predict_labels(line: None._VariableFunctionsClass.tensor, lens: Optional[torch.Tensor] = None)List[List[Tuple[int, int, int, float]]]

Performs a forward pass on a torch tensor of a line with shape (N, C, H, W) and returns a list of tuples (class, start, end, max). Max is the maximum value of the softmax layer in the region.

predict_string(line: torch.Tensor, lens: Optional[torch.Tensor] = None)List[str]

Performs a forward pass on a torch tensor of a line with shape (N, C, H, W) and returns a string of the results.

to(device)

Moves model to device and automatically loads input tensors onto it.

kraken.lib.models.load_any(fname: str, train: bool = False, device: str = 'cpu')kraken.lib.models.TorchSeqRecognizer

Loads anything that was, is, and will be a valid ocropus model and instantiates a shiny new kraken.lib.lstm.SeqRecognizer from the RNN configuration in the file.

Currently it recognizes the following kinds of models:

  • pyrnn models containing BIDILSTMs

  • protobuf models containing converted python BIDILSTMs

  • protobuf models containing CLSTM networks

Additionally an attribute ‘kind’ will be added to the SeqRecognizer containing a string representation of the source kind. Current known values are:

  • pyrnn for pickled BIDILSTMs

  • clstm for protobuf models generated by clstm

Parameters
  • fname (str) – Path to the model

  • train (bool) – Enables gradient calculation and dropout layers in model.

  • device (str) – Target device

Returns

A kraken.lib.models.TorchSeqRecognizer object.

kraken.lib.vgsl module

VGSL plumbing

class kraken.lib.vgsl.TorchVGSLModel(spec: str)

Bases: object

Class building a torch module from a VSGL spec.

The initialized class will contain a variable number of layers and a loss function. Inputs and outputs are always 4D tensors in order (batch, channels, height, width) with channels always being the feature dimension.

Importantly this means that a recurrent network will be fed the channel vector at each step along its time axis, i.e. either put the non-time-axis dimension into the channels dimension or use a summarizing RNN squashing the time axis to 1 and putting the output into the channels dimension respectively.

input

Expected input tensor as a 4-tuple.

Type

tuple

nn

Stack of layers parsed from the spec.

Type

torch.nn.Sequential

criterion

Fully parametrized loss function.

Type

torch.nn.Module

user_metdata

dict with user defined metadata. Is flushed into model file during saving/overwritten by loading operations.

Type

dict

one_channel_mode

Field indicating the image type used during training of one-channel images. Is ‘1’ for models trained on binarized images, ‘L’ for grayscale, and None otherwise.

Type

str

add_codec(codec: kraken.lib.codec.PytorchCodec)None

Adds a PytorchCodec to the model.

append(idx: int, spec: str)None

Splits a model at layer idx and append layers spec.

New layers are initialized using the init_weights method.

Parameters
  • idx (int) – Index of layer to append spec to starting with 1. To select the whole layer stack set idx to None.

  • spec (str) – VGSL spec without input block to append to model.

build_conv(input: Tuple[int, int, int, int], block: str)Union[Tuple[None, None, None], Tuple[Tuple[int, int, int, int], str, Callable]]

Builds a 2D convolution layer.

build_maxpool(input: Tuple[int, int, int, int], block: str)Union[Tuple[None, None, None], Tuple[Tuple[int, int, int, int], str, Callable]]

Builds a maxpool layer.

build_output(input: Tuple[int, int, int, int], block: str)Union[Tuple[None, None, None], Tuple[Tuple[int, int, int, int], str, Callable]]

Builds an output layer.

build_reshape(input: Tuple[int, int, int, int], block: str)Union[Tuple[None, None, None], Tuple[Tuple[int, int, int, int], str, Callable]]

Builds a reshape layer

build_rnn(input: Tuple[int, int, int, int], block: str)Union[Tuple[None, None, None], Tuple[Tuple[int, int, int, int], str, Callable]]

Builds an LSTM/GRU layer returning number of outputs and layer.

eval()None

Sets the model to evaluation/inference mode, disabling dropout and gradient calculation.

get_layer_name(layer: str, name: Optional[str] = None)str

Generates a unique identifier for the layer optionally using a supplied name.

Parameters
  • layer (str) – Identifier of the layer type

  • name (str) – user-supplied {name} with {} that need removing.

Returns

(str) network unique layer name

init_weights(idx: slice = slice(0, None, None))None

Initializes weights for all or a subset of layers in the graph.

LSTM/GRU layers are orthogonally initialized, convolutional layers uniformly from (-0.1,0.1).

Parameters

idx (slice) – A slice object representing the indices of layers to initialize.

classmethod load_clstm_model(path: str)

Loads an CLSTM model to VGSL.

classmethod load_model(path: str)

Deserializes a VGSL model from a CoreML file.

Parameters

path (str) – CoreML file

Returns

A TorchVGSLModel instance.

Raises
  • KrakenInvalidModelException if the model data is invalid (not a

  • string, protobuf file, or without appropriate metadata)

  • FileNotFoundError if the path doesn't point to a file.

classmethod load_pronn_model(path: str)

Loads an pronn model to VGSL.

classmethod load_pyrnn_model(path: str)

Loads an pyrnn model to VGSL.

resize_output(output_size: int, del_indices: Optional[Iterable] = None)None

Resizes an output layer.

Parameters
  • output_size (int) – New size/output channels of last layer

  • del_indices (list) – list of outputs to delete from layer

save_model(path: str)

Serializes the model into path.

Parameters

path (str) – Target destination

static set_layer_name(layer: str, name: str)str

Sets the name field of an VGSL layer definition.

Parameters
  • layer (str) – VGSL definition

  • name (str) – Layer name

set_num_threads(num: int)None

Sets number of OpenMP threads to use.

train()None

Sets the model to training mode (enables dropout layers and disables softmax on CTC layers).

kraken.lib.xml module

ALTO/Page data loaders for segmentation training

kraken.lib.xml.parse_alto(filename)

Parses an ALTO file, returns the baselines defined in it, and loads the referenced image.

Parameters

filename (str) – path to an ALTO file.

Returns

impath, lines: [{‘boundary’: [[x0, y0], …], ‘baseline’: [[x0, y0], …]}, {…], ‘text’: ‘apdjfqpf’, ‘script’: ‘script_type’}, regions: {‘region_type_0’: [[[x0, y0], …], …], …}, ‘base_dir’: None}

Return type

A dict {‘image’

kraken.lib.xml.parse_page(filename)

Parses a PageXML file, returns the baselines defined in it, and loads the referenced image.

Parameters

filename (str) – path to a PageXML file.

Returns

impath, lines: [{‘boundary’: [[x0, y0], …], ‘baseline’: [[x0, y0], …]}, {…], ‘text’: ‘apdjfqpf’, ‘script’: ‘script_type’}, regions: {‘region_type_0’: [[[x0, y0], …], …], …}}

Return type

A dict {‘image’

kraken.lib.xml.parse_xml(filename)

Parses either a PageXML or ALTO file with autodetermination of the file format.

Parameters

filename (str) – path to an XML file.

Returns

impath, lines: [{‘boundary’: [[x0, y0], …], ‘baseline’: [[x0, y0], …]}, {…], ‘text’: ‘apdjfqpf’, ‘script’: ‘script_type’}, regions: {‘region_type_0’: [[[x0, y0], …], …], …}, ‘base_dir’: None}

Return type

A dict {‘image’

kraken.lib.codec

pytorch compatible codec with many-to-many mapping between labels and graphemes.

class kraken.lib.codec.PytorchCodec(charset: Union[Dict[str, Sequence[int]], Sequence[str], str])

Bases: object

Translates between labels and graphemes.

add_labels(charset: Union[Dict[str, Sequence[int]], Sequence[str], str])kraken.lib.codec.PytorchCodec

Adds additional characters/labels to the codec.

charset may either be a string, a list or a dict. In the first case each code point will be assigned a label, in the second case each string in the list will be assigned a label, and in the final case each key string will be mapped to the value sequence of integers. In the first two cases labels will be assigned automatically.

As 0 is the blank label in a CTC output layer, output labels and input dictionaries are/should be 1-indexed.

Parameters

charset (unicode, list, dict) – Input character set.

decode(labels: Sequence[Tuple[int, int, int, float]])List[Tuple[str, int, int, float]]

Decodes a labelling.

Given a labelling with cuts and confidences returns a string with the cuts and confidences aggregated across label-code point correspondences. When decoding multilabels to code points the resulting cuts are min/max, confidences are averaged.

Parameters

labels (list) – Input containing tuples (label, start, end, confidence).

Returns

A list of tuples (code point, start, end, confidence)

Return type

list

encode(s: str)torch.IntTensor

Encodes a string into a sequence of labels.

Parameters

s (str) – Input unicode string

Returns

(torch.IntTensor) encoded label sequence

Raises

KrakenEncodeException if encoding fails.

max_label()int

Returns the maximum label value.

merge(codec: kraken.lib.codec.PytorchCodec)Tuple[kraken.lib.codec.PytorchCodec, Set]

Transforms this codec (c1) into another (c2) reusing as many labels as possible.

The resulting codec is able to encode the same code point sequences while not necessarily having the same labels for them as c2. Retains matching character -> label mappings from both codecs, removes mappings not c2, and adds mappings not in c1. Compound labels in c2 for code point sequences not in c1 containing labels also in use in c1 are added as separate labels.

Parameters

codec (kraken.lib.codec.PytorchCodec) –

Returns

A merged codec and a list of labels that were removed from the original codec.

kraken.lib.train module

Training loop interception helpers

class kraken.lib.train.EarlyStopping(min_delta: Optional[float] = None, lag: int = 1000)

Bases: kraken.lib.train.TrainStopper

Early stopping to terminate training when validation loss doesn’t improve over a certain time.

trigger()bool

Function that raises a KrakenStopTrainingException after if the abort condition is fulfilled.

update(val_loss: float)None

Updates the internal validation loss state and increases counter by one.

class kraken.lib.train.EpochStopping(epochs: int)

Bases: kraken.lib.train.TrainStopper

Dumb stopping after a fixed number of iterations.

trigger()bool

Function that raises a KrakenStopTrainingException after if the abort condition is fulfilled.

update(val_loss: float)None

Only update internal best iteration

class kraken.lib.train.KrakenTrainer(model: kraken.lib.vgsl.TorchVGSLModel, optimizer: torch.optim.optimizer.Optimizer, device: str = 'cpu', filename_prefix: str = 'model', event_frequency: float = 1.0, train_set: Optional[torch.utils.data.dataloader.DataLoader] = None, val_set=None, stopper=None, loss_fn=<function recognition_loss_fn>, evaluator=<function recognition_evaluator_fn>)

Bases: object

Class encapsulating the recognition model training process.

classmethod recognition_train_gen(hyper_params: Optional[Dict] = None, progress_callback: Callable[[str, int], Callable[[None], None]] = <function KrakenTrainer.<lambda>>, message: Callable[[str], None] = <function KrakenTrainer.<lambda>>, output: str = 'model', spec: str = '[1,48,0,1 Cr4,2,32,4,2 Gn32 Cr4,2,64,1,1 Gn32 Mp4,2,4,2 Cr3,3,128,1,1 Gn32 Mp1,2,1,2 S1(1x0)1,3 Lbx256 Do0.5 Lbx256 Do0.5 Lbx256 Do0.5]', append: Optional[int] = None, load: Optional[str] = None, device: str = 'cpu', reorder: Union[bool, str] = True, training_data: Optional[Sequence[Dict]] = None, evaluation_data: Optional[Sequence[Dict]] = None, preload: Optional[bool] = None, threads: int = 1, load_hyper_parameters: bool = False, repolygonize: bool = False, force_binarization: bool = False, format_type: str = 'path', codec: Optional[Dict] = None, resize: str = 'fail', augment: bool = False)

This is an ugly constructor that takes all the arguments from the command line driver, finagles the datasets, models, and hyperparameters correctly and returns a KrakenTrainer object.

Setup parameters (load, training_data, evaluation_data, ….) are named, model hyperparameters (everything in kraken.lib.default_specs.RECOGNITION_HYPER_PARAMS) are in in the hyper_params argument.

Parameters
  • hyper_params (dict) – Hyperparameter dictionary containing all fields from kraken.lib.default_specs.RECOGNITION_HYPER_PARAMS

  • progress_callback (Callable) – Callback for progress reports on various computationally expensive processes. A human readable string and the process length is supplied. The callback has to return another function which will be executed after each step.

  • message (Callable) – Messaging printing method for above log but below warning level output, i.e. infos that should generally be shown to users.

  • **kwargs – Setup parameters, i.e. CLI parameters of the train() command.

Returns

A KrakenTrainer object.

classmethod segmentation_train_gen(hyper_params: Optional[Dict] = None, load_hyper_parameters: bool = False, progress_callback: Callable[[str, int], Callable[[None], None]] = <function KrakenTrainer.<lambda>>, message: Callable[[str], None] = <function KrakenTrainer.<lambda>>, output: str = 'model', spec: str = '[1,1200,0,3 Cr7,7,64,2,2 Gn32 Cr3,3,128,2,2 Gn32 Cr3,3,128 Gn32 Cr3,3,256 Gn32 Cr3,3,256 Gn32 Lbx32 Lby32 Cr1,1,32 Gn32 Lby32 Lbx32]', load: Optional[str] = None, device: str = 'cpu', training_data: Optional[Sequence[Dict]] = None, evaluation_data: Optional[Sequence[Dict]] = None, threads: int = 1, force_binarization: bool = False, format_type: str = 'path', suppress_regions: bool = False, suppress_baselines: bool = False, valid_regions: Optional[Sequence[str]] = None, valid_baselines: Optional[Sequence[str]] = None, merge_regions: Optional[Dict[str, str]] = None, merge_baselines: Optional[Dict[str, str]] = None, bounding_regions: Optional[Sequence[str]] = None, resize: str = 'fail', augment: bool = False, topline: bool = False)

This is an ugly constructor that takes all the arguments from the command line driver, finagles the datasets, models, and hyperparameters correctly and returns a KrakenTrainer object.

Setup parameters (load, training_data, evaluation_data, ….) are named, model hyperparameters (everything in kraken.lib.default_specs.SEGMENTATION_HYPER_PARAMS) are in in the hyper_params argument.

Parameters
  • hyper_params (dict) – Hyperparameter dictionary containing all fields from kraken.lib.default_specs.SEGMENTATION_HYPER_PARAMS

  • progress_callback (Callable) – Callback for progress reports on various computationally expensive processes. A human readable string and the process length is supplied. The callback has to return another function which will be executed after each step.

  • message (Callable) – Messaging printing method for above log but below warning level output, i.e. infos that should generally be shown to users.

  • **kwargs – Setup parameters, i.e. CLI parameters of the train() command.

Returns

A KrakenTrainer object.

class kraken.lib.train.NoStopping

Bases: kraken.lib.train.TrainStopper

Never stops training.

trigger()bool

Function that raises a KrakenStopTrainingException after if the abort condition is fulfilled.

update(val_loss: float)None

Only update internal best iteration

class kraken.lib.train.TrainScheduler(optimizer: torch.optim.optimizer.Optimizer)

Bases: object

Implements learning rate scheduling.

add_phase(steps: int, annealing_fn: Optional[Callable] = None)None

Adds a new phase to the scheduler.

Parameters
  • steps (int) – Number of step for this scheduler. Can be epochs or iteration depending on the scheduler.

  • max_lr (float) – Peak learning rate

  • annealing_fn (Callable) – LR change function.

batch_step(loss=None)None

Performs an optimization step.

epoch_step(val_loss=None)None

Performs an optimization step.

kraken.lib.dataset module

Utility functions for data loading and training of VGSL networks.

class kraken.lib.dataset.BaselineSet(imgs: Optional[Sequence[str]] = None, suffix: str = '.path', line_width: int = 4, im_transforms: Callable[[Any], torch.Tensor] = Compose(), mode: str = 'path', augmentation: bool = False, valid_baselines: Optional[Sequence[str]] = None, merge_baselines: Optional[Dict[str, Sequence[str]]] = None, valid_regions: Optional[Sequence[str]] = None, merge_regions: Optional[Dict[str, Sequence[str]]] = None)

Bases: Generic[torch.utils.data.dataset.T_co]

Dataset for training a baseline/region segmentation model.

add(image: Union[str, PIL.Image.Image], baselines: Optional[List[List[List[Tuple[int, int]]]]] = None, regions: Optional[Dict[str, List[List[Tuple[int, int]]]]] = None, *args, **kwargs)

Adds a page to the dataset.

Parameters
  • im (path) – Path to the whole page image

  • baseline (dict) – A list containing dicts with a list of coordinates and script types [{‘baseline’: [[x0, y0], …, [xn, yn]], ‘script’: ‘script_type’}, …]

  • regions (dict) – A dict containing list of lists of coordinates {‘region_type_0’: [[x0, y0], …, [xn, yn]]], ‘region_type_1’: …}.

class kraken.lib.dataset.GroundTruthDataset(split: Callable[[str], str] = <function default_split>, suffix: str = '.gt.txt', normalization: Optional[str] = None, whitespace_normalization: bool = True, reorder: Union[bool, str] = True, im_transforms: Callable[[Any], torch.Tensor] = Compose( ), preload: bool = True, augmentation: bool = False)

Bases: Generic[torch.utils.data.dataset.T_co]

Dataset for training a line recognition model.

All data is cached in memory.

add(*args, **kwargs)None

Adds a line-image-text pair to the dataset.

Parameters

image (str) – Input image path

add_loaded(image: PIL.Image.Image, gt: str)None

Adds an already loaded line-image-text pair to the dataset.

Parameters
  • image (PIL.Image.Image) – Line image

  • gt (str) – Text contained in the line image

encode(codec: Optional[kraken.lib.codec.PytorchCodec] = None)None

Adds a codec to the dataset and encodes all text lines.

Has to be run before sampling from the dataset.

no_encode()None

Creates an unencoded dataset.

parse(image: Union[str, PIL.Image.Image], *args, **kwargs)Dict

Parses a sample for this dataset.

This is mostly used to parallelize populating the dataset.

Parameters

image (str) – Input image path

class kraken.lib.dataset.PolygonGTDataset(normalization: Optional[str] = None, whitespace_normalization: bool = True, reorder: Union[bool, str] = True, im_transforms: Callable[[Any], torch.Tensor] = Compose(), preload: bool = True, augmentation: bool = False)

Bases: Generic[torch.utils.data.dataset.T_co]

Dataset for training a line recognition model from polygonal/baseline data.

add(*args, **kwargs)

Adds a line to the dataset.

Parameters
  • im (path) – Path to the whole page image

  • text (str) – Transcription of the line.

  • baseline (list) – A list of coordinates [[x0, y0], …, [xn, yn]].

  • boundary (list) – A polygon mask for the line.

encode(codec: Optional[kraken.lib.codec.PytorchCodec] = None)None

Adds a codec to the dataset and encodes all text lines.

Has to be run before sampling from the dataset.

no_encode()None

Creates an unencoded dataset.

parse(image: Union[str, PIL.Image.Image], text: str, baseline: List[Tuple[int, int]], boundary: List[Tuple[int, int]], *args, **kwargs)

Parses a sample for the dataset and returns it.

This function is mainly uses for parallelized loading of training data.

Parameters
  • im (path) – Path to the whole page image

  • text (str) – Transcription of the line.

  • baseline (list) – A list of coordinates [[x0, y0], …, [xn, yn]].

  • boundary (list) – A polygon mask for the line.

kraken.lib.dataset.compute_error(model: kraken.lib.models.TorchSeqRecognizer, validation_set: Iterable[Dict[str, torch.Tensor]])Tuple[int, int]

Computes error report from a model and a list of line image-text pairs.

Parameters
Returns

A tuple with total number of characters and edit distance across the whole validation set.

kraken.lib.dataset.generate_input_transforms(batch: int, height: int, width: int, channels: int, pad: int, valid_norm: bool = True, force_binarization=False)torchvision.transforms.transforms.Compose

Generates a torchvision transformation converting a PIL.Image into a tensor usable in a network forward pass.

Parameters
  • batch (int) – mini-batch size

  • height (int) – height of input image in pixels

  • width (int) – width of input image in pixels

  • channels (int) – color channels of input

  • pad (int) – Amount of padding on horizontal ends of image

  • valid_norm (bool) – Enables/disables baseline normalization as a valid preprocessing step. If disabled we will fall back to standard scaling.

  • force_binarization (bool) – Forces binarization of input images using the nlbin algorithm.

Returns

A torchvision transformation composition converting the input image to the appropriate tensor.

kraken.lib.dataset.preparse_xml_data(filenames, format_type='xml', repolygonize=False)

Loads training data from a set of xml files.

Extracts line information from Page/ALTO xml files for training of recognition models.

Parameters
  • filenames (list) – List of XML files.

  • format_type (str) – Either page, alto or xml for autodetermination.

  • repolygonize (bool) – (Re-)calculates polygon information using the kraken algorithm.

Returns

text, ‘baseline’: [[x0, y0], …], ‘boundary’: [[x0, y0], …], ‘image’: PIL.Image}.

Return type

A list of dicts {‘text’

kraken.lib.segmentation module

Processing for baseline segmenter output

kraken.lib.segmentation.calculate_polygonal_environment(im: Optional[PIL.Image.Image] = None, baselines: Optional[Sequence[Sequence[Tuple[int, int]]]] = None, suppl_obj: Optional[Sequence[Sequence[Tuple[int, int]]]] = None, im_feats: Optional[numpy.array] = None, scale: Optional[Tuple[int, int]] = None, topline: bool = False)

Given a list of baselines and an input image, calculates a polygonal environment around each baseline.

Parameters
  • im (PIL.Image) – grayscale input image (mode ‘L’)

  • baselines (sequence) – List of lists containing a single baseline per entry.

  • suppl_obj (sequence) – List of lists containing additional polylines that should be considered hard boundaries for polygonizaton purposes. Can be used to prevent polygonization into non-text areas such as illustrations or to compute the polygonization of a subset of the lines in an image.

  • im_feats (numpy.array) – An optional precomputed seamcarve energy map. Overrides data in im. The default map is gaussian_filter(sobel(im), 2).

  • scale (tuple) – A 2-tuple (h, w) containing optional scale factors of the input. Values of 0 are used for aspect-preserving scaling. None skips input scaling.

  • topline (bool) – Switch to change default baseline location for offset calculation purposes. If set to False, baselines are assumed to be on the bottom of the text line and will be offset upwards, if set to True, baselines are on the top and will be offset downwards.

Returns

List of lists of coordinates. If no polygonization could be compute for a baseline None is returned instead.

kraken.lib.segmentation.compute_polygon_section(baseline, boundary, dist1, dist2)

Given a baseline, polygonal boundary, and two points on the baseline return the rectangle formed by the orthogonal cuts on that baseline segment. The resulting polygon is not garantueed to have a non-zero area.

The distance can be larger than the actual length of the baseline if the baseline endpoints are inside the bounding polygon. In that case the baseline will be extrapolated to the polygon edge.

Parameters
  • baseline (list) – A polyline ((x1, y1), …, (xn, yn))

  • boundary (list) – A bounding polygon around the baseline (same format as baseline).

  • dist1 (int) – Absolute distance along the baseline of the first point.

  • dist2 (int) – Absolute distance along the baseline of the second point.

Returns

A sequence of polygon points.

kraken.lib.segmentation.extract_polygons(im: PIL.Image.Image, bounds: Dict[str, Any])<module ‘PIL.Image’ from ‘/home/mittagessen/.miniconda3/envs/ta/lib/python3.7/site-packages/PIL/Image.py’>

Yields the subimages of image im defined in the list of bounding polygons with baselines preserving order.

Parameters
  • im (PIL.Image.Image) – Input image

  • bounds (list) – A list of tuples (x1, y1, x2, y2)

Yields

(PIL.Image) the extracted subimage

kraken.lib.segmentation.polygonal_reading_order(lines: Sequence[Tuple[List, List]], text_direction: str = 'lr', regions: Optional[Sequence[List[Tuple[int, int]]]] = None)Sequence[Tuple[List, List]]

Given a list of baselines and regions, calculates the correct reading order and applies it to the input.

Parameters
  • lines (Sequence) – List of tuples containing the baseline and its polygonization.

  • regions (Sequence) – List of region polygons.

  • text_direction (str) – Set principal text direction for column ordering. Can be ‘lr’ or ‘rl’

Returns

A reordered input.

kraken.lib.segmentation.reading_order(lines: Sequence, text_direction: str = 'lr')List

Given the list of lines (a list of 2D slices), computes the partial reading order. The output is a binary 2D array such that order[i,j] is true if line i comes before line j in reading order.

kraken.lib.segmentation.scale_polygonal_lines(lines: Sequence[Tuple[List, List]], scale: Union[float, Tuple[float, float]])Sequence[Tuple[List, List]]

Scales baselines/polygon coordinates by a certain factor.

Parameters
  • lines (Sequence) – List of tuples containing the baseline and it’s polygonization.

  • scale (float or tuple of floats) – Scaling factor

kraken.lib.segmentation.scale_regions(regions: Sequence[Tuple[List, List]], scale: Union[float, Tuple[float, float]])Sequence[Tuple[List, List]]

Scales baselines/polygon coordinates by a certain factor.

Parameters
  • lines (Sequence) – List of tuples containing the baseline and it’s polygonization.

  • scale (float or tuple of floats) – Scaling factor

kraken.lib.segmentation.vectorize_lines(im: numpy.ndarray, threshold: float = 0.17, min_length=5)

Vectorizes lines from a binarized array.

Parameters
  • im (np.ndarray) – Array of shape (3, H, W) with the first dimension being probabilities for (start_separators, end_separators, baseline).

  • threshold (float) – Threshold for baseline blob detection.

  • min_length (int) – Minimal length of output baselines.

Returns

[[x0, y0, … xn, yn], [xm, ym, …, xk, yk], … ] A list of lists containing the points of all baseline polylines.

kraken.lib.ctc_decoder

Decoders for softmax outputs of CTC trained networks.

kraken.lib.ctc_decoder.beam_decoder(outputs: numpy.ndarray, beam_size: int = 3)List[Tuple[int, int, int, float]]

Translates back the network output to a label sequence using same-prefix-merge beam search decoding as described in [0].

[0] Hannun, Awni Y., et al. “First-pass large vocabulary continuous speech recognition using bi-directional recurrent DNNs.” arXiv preprint arXiv:1408.2873 (2014).

Parameters

output (numpy.array) – (C, W) shaped softmax output tensor

Returns

A list with tuples (class, start, end, prob). max is the maximum value of the softmax layer in the region.

kraken.lib.ctc_decoder.blank_threshold_decoder(outputs: numpy.ndarray, threshold: float = 0.5)List[Tuple[int, int, int, float]]

Translates back the network output to a label sequence as the original ocropy/clstm.

Thresholds on class 0, then assigns the maximum (non-zero) class to each region.

Parameters
  • output (numpy.array) – (C, W) shaped softmax output tensor

  • threshold (float) – Threshold for 0 class when determining possible label locations.

Returns

A list with tuples (class, start, end, max). max is the maximum value of the softmax layer in the region.

kraken.lib.ctc_decoder.greedy_decoder(outputs: numpy.ndarray)List[Tuple[int, int, int, float]]

Translates back the network output to a label sequence using greedy/best path decoding as described in [0].

[0] Graves, Alex, et al. “Connectionist temporal classification: labelling unsegmented sequence data with recurrent neural networks.” Proceedings of the 23rd international conference on Machine learning. ACM, 2006.

Parameters

output (numpy.array) – (C, W) shaped softmax output tensor

Returns

A list with tuples (class, start, end, max). max is the maximum value of the softmax layer in the region.